Estoy usando la función memorizada de lodash y estoy notando un comportamiento extraño que no tiene sentido para mí.
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');Aquí está lo extraño, si uso la Opción 1, comentando la Opción 2
totalFunctionTime 0.394859 ms totalLoopTime 7.859825 msSi uso la opción 2
totalFunctionTime 0.506823 ms totalLoopTime 19.078935 msEstoy muy confundido, la Opción 1 y la Opción 2 no deberían arrojar resultados diferentes porque la función superior ya se ha memorizado, por lo que no se llama en absoluto (lo he verificado al iniciar sesión)
¿Y parece que afecta el tiempo de bucle? Lo cual no tiene nada que ver con la Opción 1 y la Opción 2 en absoluto. T Tenga en cuenta que este caso de prueba está utilizando un ciclo simple (no sucede nada dentro del ciclo)
Cualquiera puede dar razón de esto?