Sorry this question isn't too accurate. I've come across this by accident somehow: I have 4 heavy load functions HeavyOperation()1-4
that I benchmarked, all being very similar to each other, except 1 of them yields a different result in its execution time, and I cannot explain to myself why that is. They make use of promises and return a promise at some point with a resolve callback simply taking in the result of the heavy for loop. Most notably (I think) being the comparison between the 3rd and 4th one, where saving the result into another variable before returning the promise somehow makes a difference. I don't know what to make of this.
The results in this show the 4th function being twice as slow. Doubling the variable i
(using these particular values) heavily changes the results of execution time (7x slower). And a little extra.. Somehow using a value of 1100000000 for i
instead of 1000000000 is 9% faster for 1-3rd function, and 21% slower for the 4th one.
When testing please note that Firefox yields extremely inconsistent results, I used chrome which worked better for me. The entire code can be copy pasted
Is this stack/heap related? Something internal in javascript? Are promises even the reason for this to happen?
function TimeTestOperation() {
let StartTime = Date.now();
let BigNumber = HeavyOperation1();
let EndTime = Date.now();
console.log('HeavyOperation1(): ' + (EndTime - StartTime) + 'ms');
StartTime = Date.now();
BigNumber = HeavyOperation2();
EndTime = Date.now();
console.log('HeavyOperation2(): ' + (EndTime - StartTime) + 'ms');
StartTime = Date.now();
BigNumber = HeavyOperation3();
EndTime = Date.now();
console.log('HeavyOperation3(): ' + (EndTime - StartTime) + 'ms');
StartTime = Date.now();
BigNumber = HeavyOperation4();
EndTime = Date.now();
console.log('HeavyOperation4(): ' + (EndTime - StartTime) + 'ms');
}
TimeTestOperation();
// 711 ms
function HeavyOperation1() {
return new Promise(resolve => {
let a = 0;
for (let i = 0; i < 1000000000; i++) a++;
let Result = a;
resolve(Result);
});
}
// 712 ms
function HeavyOperation2() {
return new Promise(resolve => {
let a = 0;
for (let i = 0; i < 1000000000; i++) a++;
resolve(a);
});
}
// 715 ms
function HeavyOperation3() {
let a = 0;
for (let i = 0; i < 1000000000; i++) a++;
let result = a;
return new Promise(resolve => resolve(result));
}
// 1479 ms
function HeavyOperation4() {
let a = 0;
for (let i = 0; i < 1000000000; i++) a++;
return new Promise(resolve => resolve(a));
}