'Why does my for loop run slower if I change some code in memonized function?
I am using lodash memonized function and is noticing some strange behavior that does not make sense to me.
const memonizedPadStart = _.memoize((k, l) => String(k).padStart(l, '0'));
const innerHelper = _.memoize((value) => {
// Somewhere have padStart
// Option 1 cache
const str = memonizedPadStart(k, l);
// Option 2 normal
const str = String(k).padStart(l, '0'));
});
const generate = _.memoize((str) => {
// Somewhere we call innerHelper
...
const results = innerHelper(value);
...
});
// Preprocessing.
for (let i = 0; i < list.length; i += 1) {
const results = generate(list[i].str);
for (let j = 0; j < results.length; j += 1) {
}
}
// Now we test performance
let totalLoopTime = 0n;
let totalFunctionTime = 0n;
for (let i = 0; i < list.length; i += 1) {
const functionStart = process.hrtime.bigint();
const results = generate(list[i].str);
const functionTaken = process.hrtime.bigint() - functionStart;
totalFunctionTime += functionTaken;
const loopStart = process.hrtime.bigint();
for (let j = 0; j < results.length; j += 1) {
}
const loopTaken = process.hrtime.bigint() - loopStart;
totalLoopTime += loopTaken;
}
console.log('totalFunctionTime', Number(totalFunctionTime)/1000000, 'ms');
console.log('totalLoopTime', Number(totalLoopTime)/1000000, 'ms');
Here is the odd thing, if I use Option 1, commenting out Option 2
totalFunctionTime 0.394859 ms
totalLoopTime 7.859825 ms
If I use Option 2
totalFunctionTime 0.506823 ms
totalLoopTime 19.078935 ms
I am very confused, Option 1 and Option 2 should not yield different results because the upper function already been memonized so it does not get called at all (I have verified this by logging)
And it seems that it affects loop timing? Which has nothing to do with Option 1 and Option 2 at all. T Note this test case is using plain loop (nothing is happening inside the loop)
Anyone can provide reason for this?
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
