5
// Shifting the array and accessing 0
let sum = 0;
while(matrix.length > 0) {
  sum += matrix[0][0];
  matrix.shift();
}
// direct access
let sum = 0;
for (let i = 0; i < matrix.length; i++) {
  sum += matrix[i][0];
}

https://jsperf.com/shift-vs-index-access

Shifting the array and accessing 0 is faster than direct access in the given examples in the above jsPerf link.

Isn't shift() an O(n) operation?

Boann
  • 48,794
  • 16
  • 117
  • 146
ran
  • 59
  • 3
  • I'm not sure there is a guarantee that `.shift` will be `O(n)`. It would be in something like an array-backed list but it can easily be `O(1)` in a linked list. – VLAZ Jan 31 '19 at 09:54
  • Just for reference, [I added a couple of cases](https://jsperf.com/shift-vs-index-access/3) to try and control for `for` vs `while` loop. Just in case that made a difference but it still seems that `shift` is faster by the same margin even if it's executed in a `for` loop. – VLAZ Jan 31 '19 at 10:01

1 Answers1

7

No, it's not faster. It's just your benchmark being broken. The shift() operation empties the matrix array, and after the first iteration you are comparing your codes on an empty array.

When you are benchmarking code that mutates your data structure, you need to re-create the data structure on every test run. I've fixed your jsperf.com case and as expected shift is slower (notice that probably a large part of the execution time is spent on createMatrix, so in fact it's a lot slower).

Bergi
  • 630,263
  • 148
  • 957
  • 1,375
  • 1
    Thanks for correcting it. My mistake. I was trying to illustrate a real issue I've seen. I've updated your case with array of 1000 x 1000. Shift is still faster than index. https://jsperf.com/shift-vs-index-access/8 – ran Jan 31 '19 at 10:32
  • 1
    @ran That's weird, I cannot explain that. However, when you optimise `createMatrix` a bit then the `shift` run is (considerably) slower: https://jsperf.com/shift-vs-index-access/10 – Bergi Jan 31 '19 at 12:45