Writing lighter, faster JavaScript functions

Click for: original source

Nick Gard sweet article about making your JavaScript functions faster. He relies on 3 simple rules to guide him.

When it comes to JavaScript performance, there are really only three strategies for improvement: Do less, Do it less often, Do it faster

Author takes small function with an unchanging object created within the function body. While it is a small object, it is created every time the function runs. That means with every call, the function reallocates memory for an array of three items, uses it once, and then leaves it for garbage collection.

function isStooge(name) {
  const STOOGES = ['Larry', 'Curly', 'Moe'];
  return STOOGES.includes(name);
};

For static values, it would be best if they were declared once and merely referenced each time they were needed. This is not a memory leak, but it is still an unnecessary expense.

Author then suggests to use:

  • Define variable in a Closure (close to the point of use)
  • Declare variable in a Module
  • And declare variable in a Class Static Property

Author concludes that the most useful pattern of declaring an unchanging variable is in an ES6 module. The syntax is so understandable and predictable, it is almost boring. Great read!

[Read More]

Tags programming javascript nodejs frontend