Fastest way to iterate through an array.

This thread may be me just being unnecessarily paranoid and seeking optimizations that don’t exist.

But just for the sake of being thorough in my understanding I wanted to ask, is there any way to iterate through an array of ints faster than just declaring an int[ ] array and going through it with a for loop?

When you allocated an array via int[ ] that places that array on the heap, correct? And the heap is slower to retrieve from than the stack, correct? So wouldn’t an array allocated on the stack be faster than on the heap? Is there anyway to get the array to allocate on the stack? A part of me feels thats a really stupid question, but I must ask it anyways, JUST IN CASE I may not be aware of something.

Also what about static variables? Would it be faster to iterate through a static array then a non-static one?

Or anything? Any other variable modifiers I’m not aware of?

Arrays have a block of memory contiguously allocated on the heap. Your variable for the array is on the stack and points to this contiguous piece of memory.

This isn’t slow. Actually having the array in the heap can be fast. Because your array can be referenced. Moving references around is super fast because the reference only passes around the memory address, not the entire chunk of memory.

The heap and the stack are just blocks of memory. There’s nothing different about the memory of each… they’re just register addresses with values in them. It’s not like the ints in the array are boxed or anything… they’re stored in a regular contiguous block of memory as ints… just one after the other. The index denoting which of the ints you want.

Really I couldn’t think of a faster way to store a resizeable chunk of memory full of ints. I mean yeah if you had an array of like 3 ints on the stack it “might” be a teensy bit faster. But what’s the point of that. I saved a femtosecond looping over my entire array… ok?

Really, there are FAR more expensive things in unity to worry yourself with than a for loop over an array. Which is probably one of the fastest acts you can perform enumerable wise.

Maybe what we should be asking is WHY you are iterating over that array - I get the feeling you are performing a search somewheres, if that is the case, perhaps investigate a binary search algorithm: List<T>.BinarySearch Method (System.Collections.Generic) | Microsoft Learn .

The notion of finding the critical path of execution to determine if you should even be worried about optimization is a sound one, so do that first and ignore the question (unless it’s for your own education) if you find it is not on the CPoE.

yes, it is faster to use ++i instead of i++ on the for loop.
i++ creates a temp variable of i (we’ll call it x). the operator for increment is called on x, the return value is casted to type of i then stored in i.
++i calls the op increment on i and stored the return in i.
feel free to look up post and pre increment operations.

the fastest code is no code at all.

Also i should note that these kinds of things do matter in a number of places i’ve coded. Especially for software renderers and image filtering. Most of the time, the arrays cannot be sorted in any logical method other than the form at which they arrived.

actually no

in C# the compiler optimizes for loops with i++ and ++i, and they compile down to the same intermediate code.

quick google, first link, someone supplied the IL already:
http://stackoverflow.com/questions/467322/is-there-any-performance-difference-between-i-and-i-in-c

gah! C# is not like C++ >.<

This is a lesson I had to learn several times before getting it right.

Rather than worrying about heap/stack, you definitely should be looking at using a search algorithm or another data structure if you need to find a specific item within the array.

That entirely depends on how big the array is, though. :wink:

But seriously, lordofduct’s last paragraph and the quote hit the nail on the head.

in my case i’m simple minded i wouldn’t really worry about the speed of a array or a list or collections until i see it perfoming on the project. i have seen many people trying to premeditate results when it’s not implemented yet lol

I see no problem with preemptive optimizations, I look for them myself. Perhaps no one will ever notice the difference between .001 and .0001 , but telling people to use non-optimal coding techniques until it becomes a problem is bad advice IMO.

Take this for example:

for(var i:int = 0; i < max; ++i){
  var reusedValue:float = Mathf.Sqrt(((x-h)*(x-h))+((y-k)*(y-k)));
  // do something with reusedValue here
}

Setting aside the different ways to utilize the for loop, the obvious bad technique, is to continuously re-evaluate ‘reusedValue’ for every single iteration of the for loop. Will anyone notice the difference? Are there other ares which bottle neck worse than this? Does it change the fact, that this is a bad programming technique?

Just my 2 cents.

1 Like

no one said to use non-optimal coding techniques.

we said hunting for optimizations that may or may not exist is a waste of time

There is a difference

Although as stated before, these optimisations are pointless, one of the fastest ways(in pure theory) to loop through an array is to compare to zero.

for (uint i = 10; i != 0; --i)
{
	print(i);
}

If you need to access the 0 array with this method, you have to use i-1 for indexing, which is less than ideal.

(I have heard of using while(i–) for a similar loop, though I have not used it myself.)

Regardless, these things nowadays come down to which compiler you use as to what instructions they get turned into, and generally you will find that there is either zero difference, or a very very insignificant difference.
So the answer is use whatever loop makes most sense to you, or that looks the neatest, because performance-wise, there’s nothing to be found here.

I’ll admit that with unity, i’ve never found a good reason to religiously micro-optimize my code. However i don’t think micro-opts are pointless, I can say for sure that on C++, we had to cut every corner we could to get our framework running properly on educational machines. Maybe this is just because the machines running our software were expected to be 10-15 years old, but still. We ran a software renderer and could only do single core and all of our bit-blips and surface classes were RELIGIOUSLY micro-opts for every ounce of performance. In the end, it mattered greatly on the low-end machines we tested them on. Even using boost and some of their amazing containers were too slow on some machines and micro-opts pushed it just over the edge for speed.

So micro-opts isn’t something you should really worry about until your SURE thats the problem. As it turns out for C# and Unity, and maybe this is just experience that prevents the problem to begin with, but we’ve yet to encounter anything specific that needed a serious optimization run. (On that note, i just multi-threaded our png crusher / cleaner because it took too long to process an apps asset directory, which now runs through unity :smile:).

EDIT: Oh i wanted to mention loop unrolling is faster if you have a much larger collection and yoru working on intel machines arm something processors in general). If you need this kind of micro opts… should learn assembly language.