Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

217
Vistas
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?

about 4 years ago · Juan Pablo Isaza
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda