Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript: Why does this benchmark show array.shift() to be so much faster than array[i] at reading off values from an array?

A quick question only. I created the benchmark (link below), and for me at least (running chrome 18.0.1025), reading values from the front of an array using array.shift() each time seems remarkably faster than reading the values using a while/for loop and accessing them by index.

I'm sure this can't be right, as shift() has a whole lot more work to do, but at the same time I cannot see what I could have done wrong to account for this rather extreme difference?

http://jsperf.com/some-array-reading-comparisons

Thanks for reading, James

like image 507
jsdw Avatar asked Sep 14 '12 11:09

jsdw


People also ask

Which array method is faster in JavaScript?

In case of multiple iterations of the loop, and where the size of array is too large, for loop is the preference as the fastest method of elements' iteration.

Why is array faster than list?

NumPy Arrays are faster than Python Lists because of the following reasons: An array is a collection of homogeneous data-types that are stored in contiguous memory locations. On the other hand, a list in Python is a collection of heterogeneous data types stored in non-contiguous memory locations.

What is array shift in JavaScript?

Array.prototype.shift() The shift() method removes the first element from an array and returns that removed element. This method changes the length of the array.


1 Answers

You are setting up your array only once per test, and thus only the first iteration of the shift test has any data to work with. The next iterations have an empty array left from the first iteration, and terminate immediately.

Here is the fixed test suite, where the mutating algorithms work on a copy of the data. The shift algorithm predictably comes last in performance.

like image 100
lanzz Avatar answered Oct 17 '22 13:10

lanzz