- Home /
Performance - Calculating Length in loops
Hi,
does script calculate length of an array every cycle?
For example in a loop
for (int i = 0; i < ArrayName.Length; i++)
is "ArrayName.Length" calculated every iteration?
I think it is, because if you set it to
i < i + 1
You would get an infinite loop
Answer by Kiwasi · Nov 03, 2014 at 07:09 PM
ArrayName.length is looked up every iteration. But due to the fixed length nature of arrays it's not calculate every time.
This is only valid so long as you don't resize the array in your loop.
For other reasons it's generally considered bad practice to add or remove an item from a collection while iterating over it.
This looks more realistic since it is a commonly used feature. It would be strange if they have a thing like garbage collector but no array length storing.
You could easily run a bench mark to compare. But my gut feel is the performance increase will barely be worth the effort.
Answer by Tanshaydar · Nov 03, 2014 at 06:53 PM
From Google's JavaScript styling, I noticed they use
for( var i = 0, ii = array.length; i < ii; i++) { // some stuff here }
So I assume that, it calculates array length each iteration, which is actually a performance loss. I am not sure if it is the same for C#, but considering the syntax, it pretty much calls the array length each iteration (maybe it holds that somewhere and does not count it each time, I don't know, Unity's compiler is a mystery to me, and it uses .Net 2.0 which is pretty old).
By convention, I do not call array length each iteration but I do not see any performance difference in my work either.
Your answer

Follow this Question
Related Questions
Multiple Cars not working 1 Answer
Distribute terrain in zones 3 Answers
Component.GetComponent() very slow 0 Answers
Code execution is slower in Unity then outside of Unity 0 Answers