- Home /
How fast is "System.Array.IndexOf" on iPhone?
hi there!
I was wondering what would be faster, using for(...) or foreach(...) on arrays in C# on iPhone like
foreach (GameObject foo in bArray) int index = System.Array.IndexOf(bArray, foo);
or
for(int i=0; i<= bArray.length-1; i++) int index = i;
thnx!
What does making a test, running it on the device, and using the profiler tell you?
Your for loop looks a little funny though. No need to decrement length. for(int i=0; i < bArray.length; i++)
Answer by Statement · Mar 24, 2011 at 11:10 AM
A for loop is faster and should be used when you want to make use of the index. Any index searching functions just add overhead.
for(int i=0; i < bArray.length; i++)
int index = i;
IndexOf need to walk through the array so your time complexity would be squared. So for large lists it will become slower (Well I'd be surprised if the foreach ever would be faster)
foreach (GameObject foo in bArray) int index = System.Array.IndexOf(bArray, foo); // <- for/each inside
// basically the same as:
foreach (GameObject foo in bArray) { int index = -1; for (int i = 0; i < bArray.length; ++i) { if (bArray[i] == foo) { index = i; break; } } }
So you can imagine it is quite slower.
Small note about "A for loop is faster" - it depends on circumstance. With a native array, the CIL created is the same for both foreach and for, meaning identical speed.
While it's true that compilers can make use of some quick cheats for stuff like arrays, a foreach works on an IEnumerator, meaning callbacks for testing and enumerating the set. I havnen't personally checked out the generated IL, I'll take your word for it. But foreach on other classes will cause a slight overhead. The overhead is so small it often have no practical value, but still it is overhead.
I often use foreach loops if i just need to iterate through the elements, but when I need the corresponding index I'll always use a "normal" for(int i ...)
loop. IndexOf on native arrays is quite slow depending on the element count. IndexOf will iterate through the array until it finds the element. In search optimised classes like Dictionary it's quite fast but still an overhead.
Answer by Mike 3 · Mar 24, 2011 at 10:21 AM
Your first example makes little sense, so the second one
IndexOf should be relatively fast, but it's not for getting the count in a loop - use a count variable for that and increment it each time
Regarding for vs foreach - it depends.
Usually you'll want to use whichever is easiest to read, there's very little (if any) difference in speed for native arrays
Your answer
Follow this Question
Related Questions
Code differences between Unity Editor and real iPhone ; a String.Split or IndexOf problem. 2 Answers
Optimize my game? 2 Answers
does ios require physical phone 1 Answer
Zero-ing the Input.acceleration.z 0 Answers
Unity modules for iOS? 1 Answer