简体   繁体   中英

Time first call function in node

I have the following code:

 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); } 

When I run locally on the nodejs (v8.9.3), the result in the console:

Duration(0): 4ms

Duration(1): 0ms

Duration(2): 0ms

Duration(3): 0ms

Duration(4): 0ms

My Question: Why does the first call of 'findPair' take 4ms and other calls only 0ms?

When the loop runs the first time the JavaScript engine (Google's V8) interprets the code, compiles it and executes. However, code that runs more often will have it's compiled code optimized and cached so that subsequent runs of that code can run faster. Code inside loops would be a good example of such code that runs often.

Unless you fiddle with prototypes and things that could make that cached code invalid, it'll keep running that cached code which is a lot faster than interpreting the code every time it runs.

There are a lot of smart things V8 does to make your code run faster, if you are interested in this stuff I'd highly recommend reading the sources for my answer:

Dynamic Memory and V8 with JavaScript

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

Before beginning, better time measurement is:

for (let i = 0; i < 5; i++) {
    console.time('timer '+i);
    findPair(arr, sum);
    console.timeEnd('timer ' + i);
}

...

The first function call is slower, probably because V8 dynamically create hidden classes behind the scenes, and (initially) puts function into it.

More information on https://github.com/v8/v8/wiki/Design%20Elements#fast-property-access

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM