Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

219
Visualizações
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 à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda