lulurk
lulurk

Reputation: 35

In node.js, why does the second call to a function takes considerably less time than the first?

const {performance} = require('perf_hooks');

const nemo = ['nemo'];

function findNemoArray(array) {
  let t0 = performance.now();
  for (let i = 0; i < array.length; ++i) {
    if (array[i] === 'nemo') {
      console.log("Found nemo")
    }
  }
  let t1 = performance.now();
  console.log("Call to find nemo took", t1-t0, "milliseconds");
}

findNemoArray(nemo);
findNemoArray(nemo);

Output:

$ node findNemo.js
Found nemo
Call to find nemo took 6.692564999684691 milliseconds
Found nemo
Call to find nemo took 0.09663600008934736 milliseconds

I don't understand why whould the second call take far less time than the first call?

Upvotes: 2

Views: 63

Answers (1)

Manuel Spigolon
Manuel Spigolon

Reputation: 12930

It is a v8 engine optimization.

You may go deeper reading the v8 profiling and the Ignition and Turboban pipeline (used by Nodejs too of course)

node --prof yourScript.js
# it will produce a log file that you can read by
node --prof-process isolate-00000221B52EB170-26268-v8.log > readable.txt

Upvotes: 2

Related Questions