// 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
在上述 jsPerf 链接中的示例中,移位数组并访问 0 比直接访问更快。
shift()
不是一个 O(n)
操作吗?
.shift
操作一定是O(n)
的。在类似于基于数组的列表中,它可能是O(n)
的,但在链表中很容易就能做到O(1)
。 - VLAZfor
和while
循环。以防万一这会有所不同,但似乎即使在for
循环中执行,shift
的速度也比相同的边距更快。 - VLAZ