Javascript: Why does this test show that array.shift () will be much faster than array [i] when reading values โ€‹โ€‹from an array?

Quick question. I created a benchmark (link below), and for me at least (running chrome 18.0.1025), reading values โ€‹โ€‹from the front array using array.shift () every time seems surprisingly faster than reading values โ€‹โ€‹using while / for loop and access to them by index.

I am sure this cannot be right, since shift () does a lot more work, but at the same time I donโ€™t see what I could have done wrong to explain this rather big difference?

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

Thanks for reading James

+7
source share
1 answer

You set up your array only once for each test, and therefore only the first iteration of the shift test has any data to work with. The following iterations have an empty array left over from the first iteration, and immediately terminate.

Here is a fixed set of tests where mutation algorithms work on a copy of the data. The shift algorithm is expected to be the last in performance.

+7
source

All Articles