1
\$\begingroup\$

As the title mentions I am interested in LINQ performance in Unity. When is it okay and when is it not okay to use it?

As I understand it is bad to use it in something like Update which gets called every frame; that makes sense. But what about using it in events and methods that are not called on every frame but only when something specific happens?

\$\endgroup\$
3
  • \$\begingroup\$ Oversimplifying rules like "never use in Update, but it's fine everywhere else" are dangerous. \$\endgroup\$
    – Philipp
    Oct 5 at 11:01
  • \$\begingroup\$ Yeah that is why I am asking this, to try and avoid some mistakes \$\endgroup\$
    – Ivan
    Oct 5 at 11:03
  • 1
    \$\begingroup\$ Related: Read the deferred execution section - docs.microsoft.com/en-us/dotnet/framework/data/adonet/ef/… \$\endgroup\$
    – Evorlor
    Oct 5 at 12:53
2
\$\begingroup\$

You can't generalize things like that, because they always require context. A LINQ expression can include a lot of different operations, and operate on very different quantities of data.

Any LINQ operators which transform one sequence of values into another (like .Select or .Filter) will have to do at least one complete loop over the input sequence. Those which return only one element (like .First(predicate)) will at least loop until they found what they were looking for. So their runtime complexity is at least linear to the size of the collection. And operators like .Sort or .Group which needs to jump back and forth over the input set will have runtime complexity which is worse than linear. The documentation unfortunately does not give much information about which operator has which big-O runtime complexity. But with some theoretical knowledge of computer science or practical experience in programming it's pretty easy to make an educated guess about what you can expect from an implementation which is not optimized for any particular use-case.

Also, you can not expect LINQ to do any form of caching. So if you repeat the same operation over and over again even though the data won't have changed, then you might be wasting a lot of CPU cycles.

So the bottom-line is: LINQ isn't magic. Be aware of what kind of loops will need to happen behind the scenes when you perform a LINQ operation and the amount of data those loops will have to loop over.

\$\endgroup\$
2
\$\begingroup\$

Profile your code and see for yourself. Others can only speculate about your game's performance.

As a general rule of thumb: It is fine for infrequent things. Try to avoid it for per-frame operations.

\$\endgroup\$
1
  • \$\begingroup\$ The question was more of a general nature about using linq at all, but I think the other part of answer sums it up thank you. \$\endgroup\$
    – Ivan
    Oct 5 at 11:09

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.