Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
181
rated 0 times [  182] [ 1]  / answers: 1 / hits: 32323  / 11 Years ago, wed, march 27, 2013, 12:00:00

I commonly see developers use an expression like the following in JavaScript:



arr = []
arr[arr.length] = Something
arr[arr.length] = Another thing


Wouldn't push be more appropriate?



arr = []
arr.push(Something)
arr.push(Another thing)

More From » javascript

 Answers
5

I actually asked myself the same question at the start of this year. UPDATED with new test cases http://jsperf.com/array-push-vs-unshift-vs-direct-assignment/2



It appears that push is much faster in chrome, and about equal in FF. Also direct is faster in IE9, but I would be interested to see how it performs in IE10.



I would say that most developers would assume setting the length of the array, and then using direct assignment is faster, as is the case with most programming languages. But JavaScript is different. Javascript arrays aren't really arrays, they're just key/value maps just like all other JavaScript objects. So the pre-allocation is essentially falling on deaf ears.



Personally I prefer push (:


[#79328] Tuesday, March 26, 2013, 11 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
margaritakristinak

Total Points: 502
Total Questions: 127
Total Answers: 98

Location: England
Member since Mon, May 17, 2021
3 Years ago
;