Tuesday, June 27, 2006

Arrays Faster Than Objects?

I was talking with my friend Jarrad tonight and he pointed out that simply switching out an object for an array yeilded speed improvements. This got me thinking, is it true?

In my test it showed that objects are faster, but only slightly.

The test involves both an object and an array filled with seven values/properties all containing the same ammount of data. It then runs a ten-thousand iteration for loop and adds the same value to each index/property (both using a for..in loop to weed out any inaccuracies).

The results are as followed:

Object Time: 1773ms
Array Time: 1977ms


Interesting :)

3 Comments:

Blogger Jarrad Hope said...

Have you considered that maybe for in loop may work the same, as an array can be referenced by index and in a real world situation you would use a iterative loop??

Also in my work I have many objects references other objects, when simply turned to arrays and given specific index numbers to specific entries yeilded phenonomonal speeds increases. At least with spidermonkey

Tuesday, June 27, 2006 11:01:00 AM  
Anonymous Formless said...

Interesting that you should post this; a similar topic has come up recently on the Flashcoders mailing list in the thread "Array Empowerment"

I think you may be forgetting that Array inherits from Object.

When you iterate through enumerable arrays using for..in, the loop will scan the methods of the Array object in addition to all properties you have defined.

If I may quote Steven from FC:

"[...] this is the fastest for loop (but not
the fastest loop in Flash):

for (var i = len; --i -(-1); ) {}

You're going to ask why, especially given its funky syntax. Yes, it's a
for loop with only two parameters instead of three and the compiler has
no problem with it. The answer to why is explained by the guys who
wrote Flasm. If you want to learn more about how the Flash player works
and how to really optimize your code, check out Flasm.

Performance enchancers like putting the more likely result first in an
if statement, the fastest possible loop while(--a -(-1)), etc. are
explained by how Flash compiles your Actionscript into bytecode."

Thursday, July 27, 2006 7:18:00 AM  
Blogger Sam Coles said...

Very interesting Formless. I actually did test this with an incrementing for loop and it ran much slower than a for in loop.

I've known about Flasm for quite some time but never really checked it out much.

Thursday, July 27, 2006 4:11:00 PM  

Post a Comment

<< Home