- Home /
Unity profiler performance impact
So I was profiling some performance sensitive code today and I stumbled upon a weird discrepancy between two implementations that theoretically should be identical.
So the code in question is a simple for loop running on a list.
for (int i = 0; i < list.Count; i++)
Now for this syntax, profiled showed me that calls to list.Count in my ~5000 iterations over this list took 0.3ms. Now it's not much, but 5000 elements is a low number in my use-case as well so I got worried. I decided to cache list.Count so it's accessed once and not 5k times. (list count is guaranteed to not change in my method)
int count = list.Count;
for (int i = 0; i < count; i++)
And now the time dropped to 0ms and the code is faster then before. Or is it..? Because according to every source I found and MS Documentation on list.Count, calls to list.Count should be identical to caching the number and accessing a local variable.
So my question is: is it really faster to cache list.Count? or is the time displayed in profiler simply a time it took Unity to record all those calls to list.Count?
I had deep profiling enabled to even see such details in profiler
you can try and manually measure the time for your function and compare it to your profiler information. is it possible for you to share what's going on in the for loop?
Your answer
![](https://koobas.hobune.stream/wayback/20220613000146im_/https://answers.unity.com/themes/thub/images/avi.jpg)