[Javascript Performance] How to benchmark code performance

Code:

benchmark.js

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

// SETUP 🏁

let iterations = 1e7;

const a = 1;
const b = 2;

const add = (x, y) => x + y;

// 🔚 SETUP

performance.mark('start');

// EXERCISE 💪

while (iterations--) {
  add(a, b);
}

// 🔚 EXERCISE

performance.mark('end');

performance.measure('My Special Benchmark', 'start', 'end');

const [ measure ] = performance.getEntriesByName('My Special Benchmark');
console.log(measure);

 

Running in Node:

node --trace-opt benchmark.js

Running in Chrome:

Record performance

 

Why V8 engine can optimze this code:

const add = (x, y) => x + y;

Because it is simple, rerun multip times, after first time, interportor can guess that it will accpet numbers as params. So it can skip many functions for checking & parsing

posted @ 2022-12-03 22:46  Zhentiw  阅读(19)  评论(0编辑  收藏  举报