Search code examples
javascriptperformancev8

Javascript Engine Optimization


If I have the following code in Javascript:

import getTranslation from "some-library";
import getUserSettings from "some-other-library";

const getTranslatedLabel = () => {
  const translatedLabel = getTranslation("cheeseburger");
  const { enableTranslatedLabels } = getUserSettings();

  if (enableTranslatedLabels) {
     return translatedLabel;
  } else {
     return "";
  }
}

Is a javascript engine like V8 smart enough to only execute the getTranslation function if enableTranslatedLabels is true?


Solution

  • (V8 developer here.)

    The short answer is: No, don't rely on JS engines being able to eliminate or reorder calls whose results are (conditionally) unused.

    There may be certain limited cases where calls can be avoided or reordered, but that would (at least) depend on:
    (1) the caller being hot enough to get optimized,
    (2) the callee being simple enough to get inlined,
    (3) the callee not containing further calls (or those also getting inlined),
    (4) the callee not containing operations with not-statically-known side effects
    and perhaps other conditions I'm not thinking of right now.

    As a quick, intuitive counter-example: just imagine there was a console.log("getTranslation() was called") statement inside getTranslation, and a similar call in getUserSettings. Since getTranslatedLabel doesn't know whether such logging statements (or other side effects: incrementing counters, initializing things, etc) exist, it can't skip or reorder the calls, because that would change the output you'd get, which would be an incorrect transformation of your program.

    Luckily, an optimized version is at least as easily readable as your original snippet. Personally, I'd probably write it as:

    import getTranslation from "some-library";
    import getUserSettings from "some-other-library";
    
    const getTranslatedLabel = () => {
      if (!getUserSettings().enableTranslatedLabels) return "";
      return getTranslation("cheeseburger");
    }