node.js – 节点中的第一个调用时间函数

我有以下代码:

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’需要4ms而其他调用只需要0ms?

最佳答案 当循环运行时,JavaScript引擎(Google的V8)第一次解释代码,编译并执行.但是,更频繁运行的代码将对其编译代码进行优化和缓存,以便后续运行该代码可以更快地运行.循环中的代码将是经常运行的此类代码的一个很好的示例.

除非您使用可能使缓存代码无效的原型和事物,否则它将继续运行缓存代码,这比每次运行时解释代码要快得多.

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

Dynamic Memory and V8 with JavaScript

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

点赞