应该使用哪个循环进行更好的优化?
我尝试了一些测试
const arr = new Array(200).fill().map((e, i) => i);
let testArr = [];
function forLoopTest() {
const t0 = performance.now();
for (let i = arr.length - 1; i >= 0; i--) {
testArr.push(arr[i]);
}
const t1 = performance.now();
return (t1 - t0);
}
function forEachTest() {
const t0 = performance.now();
arr.forEach(i => testArr.push(i));
const t1 = performance.now();
return (t1 - t0);
}
let runTest = 10;
while (runTest > 0) {
testArr = [];
console.log(`${forLoopTest()} -- ${forEachTest()}`);
runTest--;
}
我的输出是
“ 0-0”,
“ 0-0”,
“ 0-0”,
“ 0-0.10000000111176632”,
“ 0-0”,
“ 0-0”,
“ 0-0”,
“ 0-0.10000000111176632”,
“ 0-0”,
“ 0-0”
我的问题是,它与其他stackoverflow问题完全不同