Consider the following snippets and results from running:
Snippet 1:
let final_result, final_result2;
let start = new Date();
for(let i = 0; i < 100000000; i++) {
final_result = Math.pow(i + 1, 2);
}
let end = new Date();
console.log(end - start); // Output 1
let start2 = new Date();
for(let i = 0; i < 100000000; i++) {
final_result2 = (i + 1) ** 2;
}
let end2 = new Date();
console.log(end2 - start2); // Output 2
Snippet 2:
let final_result, final_result2;
let start = new Date();
for(let i = 0; i < 100000000; i++) {
final_result = Math.pow(i, 2);
}
let end = new Date();
console.log(end - start); // Output 1
let start2 = new Date();
for(let i = 0; i < 100000000; i++) {
final_result2 = i ** 2;
}
let end2 = new Date();
console.log(end2 - start2); // Output 2
Snippet 3:
let final_result, final_result2;
function t1(){
for(let i = 0; i < 100000000; i++) {
final_result = Math.pow(i, 2);
}
}
function t2(){
for(let i = 0; i < 100000000; i++) {
final_result2 = i ** 2;
}
}
let start = new Date();
t1();
let end = new Date();
console.log(end - start); // Output 1
let start2 = new Date();
t2();
let end2 = new Date();
console.log(end2 - start2); // Output 2
Results:
Output | Firefox 88 (ms) | Edge 90 (ms) |
---|---|---|
Snippet 1 - Output 1 | 63 | 467 |
Snippet 1 - Output 2 | 63 | 487 |
Snippet 2 - Output 1 | 63 | 468 |
Snippet 2 - Output 2 | 63 | 1180 |
Snippet 3 - Output 1 | 64 | 480 |
Snippet 3 - Output 2 | 64 | 1200 |
These results were obtained consistently over numerous tests and the number being added did not affect performance, i.e. other similar operations ((i * 1) ** 2
, (i + i) ** 2
, etc.) all resulted in a speed up over just using i ** 2
. Meanwhile Math.pow
is consistent in its speed.
How can repeated calculations of (i + n) ** 2
be faster than i ** 2
when the latter has less to calculate when using a V8 browser (Edge and Chrome both had similar results), meanwhile Firefox's runtime was consistent between the 2 snippets.