# Regarding performance, when is it okay and and when is it not okay to use LINQ with Unity?

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?

• Oversimplifying rules like "never use in Update, but it's fine everywhere else" are dangerous. Oct 5 at 11:01
• Yeah that is why I am asking this, to try and avoid some mistakes
– Ivan
Oct 5 at 11:03
– Evorlor
Oct 5 at 12:53

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.