0

This is a very simple question. When adding elements to the end of a JavaScript array, do either of these forms have a speed or other optimization benefit over the other? Or does it not really matter, other than style?

(1) pageData[pageData.length] = theMember;

(2) pageData.push(theMember);

4
  • 1
    Why bother? You wouldn't notice the change anyway, I'd go for number 2. Commented Feb 13, 2014 at 11:48
  • it's not about performance only but push is better, take a look stackoverflow.com/questions/1996747/… Commented Feb 13, 2014 at 11:55
  • I think this question is stated incorrectly. It doesn't make sense to compare single push vs. length instructions, because both take nanoseconds. Performance only matters when you add elements in a loop and in such a case, push must be measured against functions that add/create multiple array elements at once, like concat, split, match. Commented Feb 13, 2014 at 12:06
  • I was, indeed, adding elements in a loop. Commented Feb 13, 2014 at 13:34

1 Answer 1

0

The tests yielded the following results in the following browsers:

Array.push

  • Google Chrome 6.0.472.63: 0.4 ms
  • Mozilla Firefox 3.6.10: 5 ms
  • Apple Safari 5.0 (7533.16): 2 ms
  • Internet Explorer 8: 21.7 ms
  • Internet Explorer 7: 66.7 ms
  • Opera 10.62: 2.7 ms

array[array.length]

  • Google Chrome 6.0.472.63: 1.2 ms
  • Mozilla Firefox 3.6.10: 0.9 ms
  • Apple Safari 5.0 (7533.16): 0.9 ms
  • Internet Explorer 8: 10.9 ms
  • Internet Explorer 7: 32.6 ms
  • Opera 10.62: 1 ms

The results speak for themselves: using an index outperforms using Push in every browser with the exception of Google's own. If cross-compatibility is a big concern for you, the utilitarian approach would be to use an index wherever possible.

Source: http://www.scottlogic.com/blog/2010/10/15/javascript-array-performance.html

Sign up to request clarification or add additional context in comments.

2 Comments

Please don't use link only answers - if the link becomes broken / page is moved then your answer won't be of use.
Nevertheless, interesting results. Thanks!

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.