简体   繁体   中英

Performance difference between function initialization locations [JavaScript]

I am curious about the performance difference between initializing a function outside a loop vs inline:

Outside the loop:

const reducer = (acc, val) => {
  // work
};

largeArray.reduce(reducer);

Inline:

largeArray.reduce((acc, val) => {
  // work
});

I encounter this kind of situation regularly, and, unless I'm going to reuse the function, it seems useful to avoid introducing another variable into my scope by using the inline version.

Is there a performance difference in these two examples or does the JS engine optimize them identically?

For example: is the inline function being created every time the loop runs and then garbage collected? And if so:

  • What kind of effect does this have on performance, and
  • Does the size of the function affect this? For example, a function that is 200 vs 30_000 unicode characters.

Are there any other differences or things I'm not considering?

Hopefully you understand my train of thought and can provide some insight about this. I realize that I can read all of the docs and source code for V8 or other engines, and I would get my answer, but that seems like an overwhelming task to understand this concept.

I did run test on jsben

SET1(random used twice): http://jsben.ch/8Dukx

SET2:(used once): http://jsben.ch/SnvxV

Setup

const arr = [ ...Array(100).keys() ];
const reducer = (acc, cur) => (acc + cur);

Test 1

let sumInline = arr.reduce((acc, cur) => (acc + cur), 0);
let sumInlineHalf = arr.slice(0, 50).reduce((acc, cur) => (acc + cur), 0);

console.log(sumInline, sumInlineHalf);

Test 2

let sumOutline = arr.reduce(reducer, 0);
let sumOutlineHalf = arr.slice(0, 50).reduce(reducer, 0);

console.log(sumOutline, sumOutlineHalf);

Be surprised

What kind of effect does this have on performance, and

None.

Does the size of the function affect this? For example, a function that is 200 vs 30_000 unicode characters.

Functions aren't executed as "unicode characters". It doesn't matter how "long" the code is.

Are there any other differences or things I'm not considering?

A very important one: Code is written for humans , not computers. And why do you even ask me?

is the inline function being created every time the loop runs and then garbage collected?

That would be unneccessary and slow. So probably: no.

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