Search Unity

Multiple IJobs vs IJobFor

Discussion in 'Entity Component System' started by jRocket, Feb 21, 2022.

  1. jRocket

    jRocket

    Joined:
    Jul 12, 2012
    Posts:
    700
    I have made an A* pathfinding system with Jobs and Burst, based on this youtube tutorial from a few years ago. It works great, but each query is an IJob that gets individually created and scheduled, and then I wait for them all to complete with JobHandle.CompleteAll(). I'm starting to see some slight slowdowns when I have many queries at the same time. Is there any performance benefit to using IJobFor or IJobParallelFor and putting all of my queries in a single job? I have looked at the profiler, and it does seem that scheduling multiple IJobs does use different worker threads, so I'm not sure what benefit IJobFor brings.

    My code for scheduling the jobs is something like this
    Code (CSharp):
    1. var jobs = new NativeList<JobHandle>(Allocator.Temp);
    2. for (int i = 0; i < count; i++)
    3. {
    4.     var job = new FindPathJob
    5.     {
    6.         ...job data here
    7.     };
    8.  
    9.     jobs.Add(job.Schedule());
    10. }
    11.  
    12. JobHandle.CompleteAll(jobs);
     
  2. Kmsxkuse

    Kmsxkuse

    Joined:
    Feb 15, 2019
    Posts:
    306
    IJobFor, in my experience, has some issues with recognizing when actions can be vectorized. Some of it is due to the stochastic (random) nature of the job stealing process (batching actions of the for loop) and thus can not be guaranteed to be vectorizable. Other part is that the Burst team has forgotten that IJobFor exists and didnt implement some of the optimization patterns of latest Burst versions (although that has been fixed either in 1.7.1 or 1.7.2).

    In your case, it'll likely be a lot better if you add that for loop inside the job itself where it can be bursted. For loop the scheduling is iffy and is not recommended as a coding pattern.
     
  3. jRocket

    jRocket

    Joined:
    Jul 12, 2012
    Posts:
    700
    The for loop there is to actually make and schedule the jobs, so I couldn't add it inside another job. In my case that loop does seem to take a lot of time- more so than executing the job itself.
    If IJobFor has issues, what is the alternative to scheduling a bunch of jobs in a loop? IJobParallelFor?
     
  4. davenirline

    davenirline

    Joined:
    Jul 7, 2010
    Posts:
    982
    Check here to see how we did it to run A* jobs in parallel. It still uses IJobParallelFor but I think it can easily be converted to IJobFor.