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 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.
March 20th, 2008 at 12:46 am
That’s funny. I was just wondering today which would be faster to use for iterating through arrays. I guess I guessed wrong.
March 25th, 2008 at 5:05 pm
I also believe there is some proof out there that ‘uint’ is actually slower than ‘int’ for “for/while” iterations.
March 31st, 2008 at 12:59 pm
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.
April 24th, 2008 at 12:16 am
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!