开发者

JavaScript inner-functions and Performance

What is the impact on running-time and memory defining a clousre vs. global-scope func开发者_运维百科tion?

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?


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.


Performance

A very tiny benchmark case:

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

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

At my machine: (5000 * 1000 times)

#1 - 700ms

#2 - 80ms

Memory

They are almost the same ...

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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜