Search Unity

Using Linq in a job

Discussion in 'Entity Component System' started by JakHussain, Jul 3, 2019.

  1. JakHussain

    JakHussain

    Joined:
    Oct 20, 2016
    Posts:
    318
    The Linq extensions are pretty useful but none of them return Unity's native collections. Would it be safe / performant to use Linq inside a job to do stuff like sort a native array of ints, get an array back from the query and use that array to construct a new native array and set that back into one of the variables of the job?

    I ask because under the hood reference types are being used inside the job but I can't find any documentation for any dos and don'ts for what happens in a job.
     
    Gibbonfiend likes this.
  2. Enzi

    Enzi

    Joined:
    Jan 28, 2013
    Posts:
    966
    Linq is based on generics, not performant and therefore I don't think it'll ever be featured with Unitys "performance by default". There are too many pitfalls in Linq that end in horrible performance. Also Linq doesn't work in iOS because it needs to be pre-compiled.

    Even with in-memory lists or arrays it performs worse compared to writing the code yourself.
    I don't know why it never got better over the years but at work I had to get rid of a lot of lazily written Linq queries just because they dragged down the system too much. Rewriting and doing exactly the same netted in better performance.

    You're better off writing a simple sorting algorithm if you need the actual speed.
    Otherwise I'd just use an Array.Sort in heap with an IComparer and send the result to jobs.
    Also question if you need to sort in the first place. Waiting for sorts is a hard barrier.
     
  3. Peter77

    Peter77

    QA Jesus

    Joined:
    Jun 12, 2013
    Posts:
    6,618
    Unity Technologies and Microsoft, among others, recommend to avoid LINQ where performance is a concern.

    https://learn.unity.com/tutorial/fixing-performance-problems

    https://docs.microsoft.com/en-us/windows/mixed-reality/performance-recommendations-for-unity
     
    Syn0_ likes this.
  4. siggigg

    siggigg

    Joined:
    Apr 11, 2018
    Posts:
    247
    +1 on LINQ being bad for perf and GC.

    However I would love to see similar utilities for working with native collections! :)
     
    Syn0_ and elmckdaddy like this.