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*;*
*obj.doSomething();*
*}*
*```*
*<p>or is it better to use </p>*
*```*
*for(var obj:type in arr)*
*obj.doSomething();*
*```*
*<p>Given a situation in which either solution is equally valid.</p>*
*<p>ie. are both as fast as the other, or not?</p>*
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
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.