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.