Great for tools. Expensive in Update.

The problem
Sorting everything to find one.
void Update(){ var target = enemies .Where( e => e.IsAlive ) .OrderBy( e => e.Distance ) .FirstOrDefault();}
To find the single closest enemy, this sorts the whole list, every frame.
Why it costs
Hidden work, every frame.
It reads like one line, but each call does real work behind the scenes.
- OrderBy
- sorts the entire list
- Lambdas + iterators
- can allocate garbage
- 60 FPS
- 60 times a second
The fix
One pass, no sort.
Enemy target = null;float best = float.MaxValue; foreach ( var e in enemies ){ if ( e.IsAlive && e.Distance < best ) { best = e.Distance; target = e; }}
A single loop that remembers the closest so far. No sorting, no garbage.
When LINQ is fine
It's not evil. It's just not free.
LINQ is great when the code runs rarely.
- Editor tools, loading
- LINQ is great ✓
- Once on an event
- LINQ is fine ✓
- Every frame
- write the loop
The rule
Keep LINQ out of the frame loop.
- Every frame
- plain loop
- Find the min
- track best so far
- Run once
- LINQ is fine