In my programs I usually have a lot of functions with the signature myFunc({ param })
. I wanted to test what was the difference between calling these functions with a new object every time or with a variable that contains an object. i.e:
myFuncA({ param: 1 });
// vs
const paramObj = { param: 1 };
myFuncB(paramObj);
So I came up with a simple test:
let a = 0;
let b = 0;
function myFuncA({ param }) {
a += param;
}
function myFuncB({ param }) {
b += param;
}
const iterations = 1e9;
console.time('myFuncA');
for(let i = 0; i < iterations; i++) {
myFuncA({ param: 1 });
}
console.timeEnd('myFuncA')
console.time('myFuncB');
const paramObj = { param: 1 };
for(let i = 0; i < iterations; i++) {
myFuncB(paramObj);
}
console.timeEnd('myFuncB');
In this test, myFuncA is consistently faster on my machine, which is counter intuitive to me.
myFuncA: 2965.320ms
myFuncB: 4271.787ms
myFuncA: 2956.643ms
myFuncB: 4251.753ms
myFuncA: 2958.409ms
myFuncB: 4269.091ms
myFuncA: 2961.827ms
myFuncB: 4270.164ms
myFuncA: 2957.438ms
myFuncB: 4278.623ms
Initially I assumed creating an object in the function call would make the iterations slower because you need to create the object, rather than pass the same object every time. But it seems to be the other way round (?).
My specs:
- 64bits i7-6500U CPU @ 2.50GHz
- Linux Mint 20
- Node v12.14.1
Why does this happen? Is there something wrong with the test?