How to do it...

Let's assume that we've identified a bottleneck in our code base, and it happens to be a function called divideByAndSum. A hypothetical flamegraph has revealed that this function is appearing over 10% of the time at stack-top over multiple samples.

The function looks like this:

function divideByAndSum (num, array) {  try {    array.map(function (item) {      return item / num    }).reduce(function (acc, item) {      return acc + item    }, 0)  } catch (err) {    // to guard for division by zero    return 0  }}

Our task now is to make this function faster.

The first step is to extract that function into its own module.

Let's create a file called slow.js:

function divideByAndSum (num, array) {  try {    array.map(function (item) {      return item / num }).reduce(function ...

Get Node Cookbook - Third Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.