DEV Community

Discussion on: Understand Memoization in 5 Minutes

Collapse
maleta profile image
Aleksandar Maletic

Good article and video!
Just wanted to note to consider using more precise way when measuring NodeJS performance with process.hrtime that returns tuple Array [seconds, nanoseconds].
When using Date and console.log in between measurements, there are additional tasks that impacts results with no need. For more complicated examples it could involve background optimization and inconsistent results.

Here is how you can use process.hrtime for your example

var st1 = process.hrtime();
inefficientSquare(40000);
var e1 = process.hrtime();
var r10 = e1[0] - st1[0];
var r11;
if (r10 > 0) { // inverting sign if execution is measured between 2 different seconds
  r11 = - e1[1] + st1[1];
} else {
  r11 = e1[1] - st1[1];
}

var st2 = process.hrtime();
inefficientSquare(40000);
var e2 = process.hrtime();
var r20 = e2[0] - st2[0];
var r21;
if (r20 > 0) { // inverting sign if execution is measured between 2 different seconds
  r21 = - e2[1] + st2[1];
} else {
  r21 = e2[1] - st2[1];
}

// this will log diff between 2 points in time in nanoseconds and will be precise if execution time is less then 1 second, for larger executions you should include r10 and r20;
console.log(r11); // o: 197783200 nanoseconds ~= 198 miliseconds
console.log(r21); // o:  200077600 ~= 200 miliseconds