Your RPG game hits 500+ inventory items. Frame time spikes. What broke?
By Fuat Can Koseoglu,
Welcome to LINQ's deferred execution - the scale-dependent performance trap. You're building an RPG inventory system. Players collect loot, items need complex scoring for rarity/power calculations, UI displays filtered results. Your LINQ queries look clean and functional. Then item count grows... What happens with 500+ inventory items: • Query creation: var items = inventory.Where(x => x.Value > 100) (Iterator created, no execution) • First use: items.Count() (Full enumeration + expensive scoring calculations) • Second use: items.Sum(x => x.Value) (Complete re-execution of filter + calculations) • Third use: items.Take(5) (Full chain executes again) • Result: Iterator recreates enumerator and re-runs expensive operations for each use Why this multiplies work in Unity specifically: • Expensive calculations recalculate per enumeration - item scoring, distance calculations, rarity weighting all re-execute • IL2CPP has limited optimization for eliminating redundant LINQ enumerations compared to desktop JIT • GC pressure from captured variables in closures + iterator state machine allocations • Inventory changes between enumerations = inconsistent results Context matters: • EF Core: Multiple DB queries, but composable • File.ReadLines(): Each enumeration reopens the file stream • Small collections: LINQ overhead negligible until hundreds of items Solutions that actually work: ✅ Materialize selectively: Add .ToList() when you'll access results multiple times ✅ Cache expensive projections: Store calculated results, not just filtered data ✅ Profile deferred queries: Single enumeration good, multiple enumeration expensive Your "clean" LINQ chains might secretly be re-executing expensive operations.