- Home /
Javascript for loops and Arrays.
For frequent access of objects from JS Arrays we assign the element of an array to a variable of defined type. When iterating through a complete array of objects is it better to use:
var arr : Array; initArrayWithObjs();
for(i=0;i<arr.length;i++) { var obj : type = arr[i]; obj.doSomething(); }
or is it better to use
for(var obj:type in arr)
obj.doSomething();
Given a situation in which either solution is equally valid.
ie. are both as fast as the other, or not?
Answer by Eric5h5 · Jul 06, 2010 at 03:59 AM
If foreach
in C# is slower, it's by such a small amount as to be insignificant. In JS, for/in
is actually faster, at least in Unity 2.6. I believe there's some memory allocation involved though, which isn't present in a normal for loop, so it's possible there might be a garbage collection penalty at some point.
But in any case, it's indeed very unlikely that the choice will have any real affect on speed most code, unless you're looping zillions of times. It's usually better to benchmark yourself instead of asking what's faster...any answers you find might be either be outdated or wrong or maybe just don't apply to your particular situation, and it takes little effort to benchmark.
(As an aside, the major difference between for/in
in JS and foreach
in C# is that you can assign to the iteration variable in for/in
but you can't in foreach
.)
--Eric
That is interesting to note about the memory allocation. The key thing for me is that the type of the object extracted from the array is defined and not deter$$anonymous$$ed at runtime. With the standard for loop I have to allocate a variable in order to do this whereas I thought that using the 'for in' version may not allocate memory whilst still predeter$$anonymous$$ing the type.
i'm not sure how the js version is implemented, but the c# version is basically syntaxical sugar for iterating through an enumerator and assigning the current value to the temporary variable, which means it's allocating slightly more than a normal for loop
Answer by Tetrad · Jul 06, 2010 at 03:09 AM
At least in C#, the foreach is slower (which I'm assuming is pretty much the same as the for in
syntax in Javascript). However the speed differences only show up when you're dealing with lists of elements of many many thousands of elements.
As with most of these "which is faster" questions, you really have to just benchmark it yourself. If you can't tell a difference, there effectively isn't a difference, and you should use the one that is the easiest to read and write.