found drama

get oblique

getting academic on the JavaScript Array

by Rob Friesel

An experiment (in part to settle something of academic debate); what is faster new Array() or [] 1?  The function for the test case:

Yes, I realize that test #2 and test #5 result in an array with a length of 2,000,000 (vs. 1,000,000 for the other 4 tests).

Now for some chart porn; results:

As usual in these kinds of performance tests, shorter bars mean better/faster performance.  (And yes, test case #5 was wildly out-of-scale when run in Firefox 2.)

Test case #3 wins out in Firefox (1.536 seconds), but test case #6 wins in both Chrome and Safari (0.313 and 0.397 seconds, respectively).  Interestingly, Safari out-performed Chrome in 4 of the 6 test cases; but Chrome came out on top overall with that 0.313 second figure for test case #6.  The trick seems to be in assigning a length to the array and then assigning values to the indices instead of just pushing the values onto the end.

But this seems to wind up not answering the original question about Array() vs. [].  So really quickly (in Chrome), I re-ran test #6 with a new “test #7” that replaced a[i] = [] with a[i] = new Array().  Console output:

Oh wait… that was basically the same as test #3…  Hooray for Array literals!

  1. Knowing full well that it’s never as simple as that.[]
  2. Due in large part to the fact that it paused execution to request my intercession.  But that doesn’t exactly bode well anyway, does it?[]

About Rob Friesel

Software engineer by day. Science fiction writer by night. Weekend homebrewer, beer educator at Black Flannel, and Certified Cicerone. Author of The PhantomJS Cookbook and a short story in Please Do Not Remove. View all posts by Rob Friesel →

2 Responses to getting academic on the JavaScript Array

Leave a Reply

Your email address will not be published. Required fields are marked *

*

*