Which loop should be use for better optimisation ?
I have tried something to test
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--;
}
My outputs are
"0 -- 0",
"0 -- 0",
"0 -- 0",
"0 -- 0.10000000111176632",
"0 -- 0",
"0 -- 0",
"0 -- 0",
"0 -- 0.10000000111176632",
"0 -- 0",
"0 -- 0"
My questions are that is quite different from other stackoverflow question
- Why execution time is different for same methods ?
- Can we assume that For loop is better as output suggested ?
- Is this right methods to test time execution ?