Don’t use Number to iterate over for-loops

A while back I read a couple of blog posts about the slowness of using uint and int to iterate through for-loops. I needed to do some testing for a little project today and found this is false.

When using the “i” variable in for(var i = 0; i < length; i++) as an input into mathematical operation, especially when doing fractions, Number is faster for obvious reasons. This was established in the posts of the previously mentioned blogs. But when simply iterating over an array which is a very common use-case for for-loops uint is faster. Here is my test setup:

var value:Object;
var arr:Array = new Array(1000000);
var length:uint = arr.length;
var startTime:Number = getTimer();

for (var i:uint = 0; i < length; i++)
	value = arr[i];

var endTime:Number = getTimer();
trace("Total Time:", endTime - startTime);

I was getting around 210 for uints and around 230 for Number. Not a big difference, but I feel dumb for always using Number for this sort of thing without even thinking about how it works.

7 Responses to “Don’t use Number to iterate over for-loops”

  1. Andrew Says:

    That’s funny. I was just wondering today which would be faster to use for iterating through arrays. I guess I guessed wrong.

  2. Jon Valliere Says:

    I also believe there is some proof out there that ‘uint’ is actually slower than ‘int’ for “for/while” iterations.

  3. Jacob Wright Says:

    The proof out there was what I linked to in the post. They were loops that were doing mathematical operations with the “i” variable. Using Number was faster in that scenario. This is less common then simply iterating over a loop.

    I found that uint is ever-so-slightly faster than int and much faster than Number if you are simply iterating over a loop.

  4. Keith Gaddis Says:

    Bjarne Stroustrop used to say, “Premature optimization is the root of all evil.” I’m not sure in common use that the difference would be THAT significant, but all the same, good information to have!

  5. jwopitz Says:

    what kind of results would you get if you were to optimize further by saying this:

    var i:uint;
    var m:uint = someArray.length;
    for (i; i < m; i++)
    { … }

    I know that doesn’t remotely sound like a huge difference but I wonder if by establishing your variables outside the for loop if you get any further performance increases.

  6. Jacob Wright Says:

    Declaring a variable inside your loop statement or outside result in the same visibility and variable type. You wouldn’t get any performance gain doing it that way.

  7. Joel Berghoff Says:

    I get slightly better results still if I use a prefix operator in the for-statement:
    for (var i:uint = 0; i < length; ++i)

    Is there a reason more people don’t do this?