Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

214
Views
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
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!