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);
输出:
$ node findNemo.js
Found nemo
Call to find nemo took 6.692564999684691 milliseconds
Found nemo
Call to find nemo took 0.09663600008934736 milliseconds
我不明白为什么第二个调用比第一个调用花费的时间要少得多?
最佳答案
这是 v8 引擎优化。
您可以深入阅读the v8 profiling和 Ignition and Turboban管道(当然 Nodejs 也使用)
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
关于javascript - 在 Node.js 中,为什么第二次调用函数所需的时间比第一次调用要少得多?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64571553/