DEV Community

Cover image for Quick tip: Outsource heavy calculations if possible
Ralf 💥🔥☄️
Ralf 💥🔥☄️

Posted on

Quick tip: Outsource heavy calculations if possible

Even if it is obvious, I see juniors doing this a lot. It happens fast if you're deep into solving a challenge. Take your time and have a second look at every piece of code you wrote.

It doesn't seem like a big deal, but if your codebase grows and performance gets a critical point in your application this small mistakes add up quickly.

Never do repetive heavy calculations in frequently called code (eg loops).
Of course only if the input to the heavy method isn't changing.

outsource heavy calculations

Top comments (1)

Collapse
 
somedood profile image
Basti Ortiz

Whenever necessary, I also employ currying for my functions so that I wouldn't have to insert the same arguments over and over again. I'm pretty sure it's a "micro-optimization", but it does save me from the verbosity.

function someHeavyComputation(n) {
  let sum = 0;
  for (let i = 0; i < n; ++I)
    sum += i;

  return function() {
    // Do something with `sum`...
  }
}

// Cache the computation
const getBigNumber = someHeavyComputation(1000);

console.log(getBigNumber());