Search code examples
javascriptgoogle-chromev8

When I execute a simple JS function twice in a row, does it cost twice the computing power?


A simplified example:

function shorten(string) {
  return string.slice(0, 3);
}

const today = "Friday";
if (shorten(today) === "Fri") {
  console.log("Oh yeah it's " + shorten(today));
}

shorten(today) is called twice here, which makes me feel bad. I believe we all run into this situation every day, and what we do is store the the value of shorten(today) in a variable first, then use that variable twice.

My question is: are modern JS engines smart enough so that I actually don't need to worry about it?


Solution

  • If you run shorten multiple times, the V8 engine has a JIT compiler that will optimize that piece of code so it runs faster the next time.

    When it runs into the same function call for the 2nd time, maybe it's able to realize it has just did the same calculation, and still have the result in memory

    What you described is known as memoization, and V8 doesn't do that. However, there are libraries out there (e.g. fast-memoize) that does.

    But you best bet is still to store the result of the computation in a variable and reference it.