Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
472 views
in Technique[技术] by (71.8m points)

closures - JavaScript inner-functions and Performance

What is the impact on running-time and memory defining a clousre vs. global-scope function?

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

I understand that Option A has the advantage of function-a-scope(Closure)...

lets say that I have 1000 functions, how would that impact both running time and memory?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

If you use inner functions, the run time has to allocate and save their contexts for any future invocation, and this happens each time the function containing them gets called. As a result, it is convenient to imagine that declaring an inner function works like constructing an object, whose members are simply the variables in the enclosing scope around that function.

This may not be all that 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 clever optimizations you can do to avoid this in some cases, for example if you only pass the function down the call stack you can allocate in the local stack space, or do some inlining etc.). However, in most circumstances it is still an allocation, so you should avoid using too many of them in busy loops or creating many inner functions.

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

My final take is that the convenience inner functions afford completely outweighs the small run time overhead, and I would say use them wherever convenient. If it turns out to be a performance bottleneck, go back and optimize them out.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...