gpt4 book ai didi

node.js - Node 中第一次调用函数的时间

转载 作者:搜寻专家 更新时间:2023-10-31 23:23:24 24 4
gpt4 key购买 nike

我有以下代码:

let startTime;
let stopTime;

const arr = [1, 2, 3, 8, 5, 0, 110, 4, 4, 16, 3, 8, 7, 56, 1, 2, 3, 8, 5, 0, 110, 16, 3, 8, 7, 56];
const sum = 63;

durationTime = (start, stop, desc) => {
let duration = (stop - start);
console.info('Duration' + ((desc !== undefined) ? '(' + desc + ')' : '') + ': ' + duration + 'ms');
};

findPair = (arr, sum) => {
let result = [];

const filterArr = arr.filter((number) => {
return number <= sum;
});

filterArr.forEach((valueFirst, index) => {
for (let i = index + 1; i < filterArr.length; i++) {
const valueSecond = filterArr[i];
const checkSum = valueFirst + valueSecond;
if (sum === checkSum) {
result.push([valueFirst, valueSecond]);
}
}
});

//console.info(result);
};

for (let i = 0; i < 5; i++) {
startTime = new Date();
findPair(arr, sum);
stopTime = new Date();

durationTime(startTime, stopTime);
}

当我在nodejs(v8.9.3)本地运行时,控制台的结果:

持续时间(0):4ms

持续时间(1):0ms

持续时间(2):0ms

持续时间(3):0ms

持续时间(4):0ms

我的问题:为什么“findPair”的第一次调用需要 4 毫秒,而其他调用只需要 0 毫秒?

最佳答案

当循环第一次运行时,JavaScript 引擎(谷歌的 V8)解释代码,编译并执行。但是,运行频率更高的代码会对其编译代码进行优化和缓存,以便该代码的后续运行可以运行得更快。 loops 内的代码就是此类经常运行的代码的一个很好的例子。

除非您摆弄原型(prototype)和可能使缓存代码无效的东西,否则它会继续运行缓存代码,这比每次运行时都解释代码要快得多。

V8 做了很多聪明的事情来让你的代码运行得更快,如果你对这些东西感兴趣,我强烈建议你阅读我的答案的来源:

Dynamic Memory and V8 with JavaScript

How JavaScript works: inside the V8 engine + 5 tips on how to write optimized code

关于node.js - Node 中第一次调用函数的时间,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47794598/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com