#SystemBase Sequential Dependency vs Independent via CombineDependencies?

1 messages · Page 1 of 1 (latest)

proper sparrow
#

EDIT: I think the reason for why one is faster than the other is because I was only looking at the System latency and that apparently does not take into account the job time. So one approach may result in faster System Update time, but might be slower overall. I'd still appreciate feedback on the approach I outlined below.

I was testing multiple ways for me to parallelize jobs within a SystemBase and learning the proper way to make sure everything was cleaned up.

(Background) What I need to do:

  • For Each Logging Station
  • Find N closest Trees
  • Do something to those trees

Since this results in nested loops where the elements in the outer loop are independent of each other, I want to parallelize the processes.

I found that this was the fastest approach for me:

foreach (LoggingStationAspect loggingStation in SystemAPI.Query<LoggingStationAspect>()) {
    NativeList<int> values = new(Allocator.TempJob);

    GetClosestTrees job = new GetClosestTrees {
        Values = values
    };
    
    _query.SetSharedComponentFilter(loggingStation.Zone);
    JobHandle firstJob = job.Schedule(_query, Dependency);

    GetClosestTreesProcessor processorJob = new GetClosestTreesProcessor {
        Values = values
    };
    JobHandle secondJob = processorJob.Schedule(firstJob);

    values.Dispose(secondJob);

    Dependency = secondJob;
}

Though my understanding is that the use of Dependency as the dependsOn in the first Job Schedule means that **all ** jobs are sequentially dependent, even the ones created by the outer loop because I'm constantly updating the System Dependency with the latest job.

My understanding is that replacing the dependsOn in the first job (and then doing a CombineDependencies at the System Dependency level) would result in the outer loop running in parallel. Like this:

foreach (LoggingStationAspect loggingStation in SystemAPI.Query<LoggingStationAspect>()) {
    NativeList<int> values = new(Allocator.TempJob);

    GetClosestTrees job = new GetClosestTrees {
        Values = values
    };
    
    _query.SetSharedComponentFilter(loggingStation.Zone);
    JobHandle firstJob = job.Schedule(_query, new JobHandle());

    GetClosestTreesProcessor processorJob = new GetClosestTreesProcessor {
        Values = values
    };
    JobHandle secondJob = processorJob.Schedule(firstJob);

    values.Dispose(secondJob);

    Dependency = JobHandle.CombineDependencies(Dependency, secondJob);
}

I expected this to be a little faster, but it was actually about 20% slower. Why might that be?

proper sparrow
#

OP edited with a note at the top that the reason for timing difference is likely because I was looking at System Update time only.