简体   繁体   中英

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM