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);

Bhavik Ambani
  • 6,557
  • 14
  • 55
  • 86
Doug Lerner
  • 1,383
  • 2
  • 17
  • 36
  • 1
    Why bother? You wouldn't notice the change anyway, I'd go for number 2. – Matteo Tassinari Feb 13 '14 at 11:48
  • it's not about performance only but push is better, take a look http://stackoverflow.com/questions/1996747/add-new-value-to-an-existing-array-in-javascript – Ehsan Feb 13 '14 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`. – georg Feb 13 '14 at 12:06
  • I was, indeed, adding elements in a loop. – Doug Lerner Feb 13 '14 at 13:34

1 Answers1

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

Maksim Gladkov
  • 3,051
  • 1
  • 14
  • 16