JavaScript内部函数和性能 [英] JavaScript inner-functions and Performance

查看:93
本文介绍了JavaScript内部函数和性能的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

对运行时和内存定义clousre与全局范围函数的影响是什么?

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

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

$ b b

我明白选项A有function-a-scope(Closure)的优点...

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

我说有1000个函数,如何影响运行时和内存?

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.

因此,为了回答你的问题,选项B一般会更快。

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.

这篇关于JavaScript内部函数和性能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆