// 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?
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).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With