JavaScript internal functions and performance

What is the effect on runtime and memory that determines clousre vs. global-scope?

function a(){ //functions (option A) } //functions(option B) 

I understand that option A takes advantage of the-a-scope (Closure) function ...

lets say that I have 1000 functions, how will this affect both the runtime and the memory?

+4
source share
2 answers

If you use internal functions, the runtime must allocate and save their contexts for any subsequent call, and this happens every time the function that calls them is called. As a result, it is convenient to imagine that the declaration of an internal function works like building an object whose members are simply variables in the covering area around this function.

This may not be so bad if you do it infrequently, since the amount of memory is about the same as allocating an object on the heap; (and there are some smart optimizations that you can do to avoid this in some cases, for example, if you only pass a function down the call stack that you can select on the local stack, or do some insertion, etc.). However, in most cases this is still a distribution, so you should avoid using too many of them in busy cycles or creating many internal functions.

So, to answer your question, option B would be faster overall. But don't let this dissuade you!

My final result is that the internal convenience features allow you to completely outweigh the small overhead time, and I would say that they will use them wherever convenient. If this turns out to be a performance bottleneck, go back and optimize them.

+3
source

Performance

A very small test example:

# 1 internal function: http://jsfiddle.net/bMHgc/

# 2 function outside: http://jsfiddle.net/sAVZn/

By my car: (5000 * 1000 times)

# 1 - 700 ms

# 2 - 80 ms

Memory

They are almost the same ...

I would recommend option A, if possible, as it can make your code cleaner.

-1
source

Source: https://habr.com/ru/post/949530/


All Articles