Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is shift faster than index access in this JavaScript example?

// 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?

like image 292
ran Avatar asked Jan 31 '19 09:01

ran


1 Answers

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).

like image 112
Bergi Avatar answered Oct 24 '22 10:10

Bergi