没有本地功能微观优化? [英] Is not having local functions a micro optimisation?
问题描述
将内部函数移到这个函数之外,以便每次调用函数时都不会创建它是微优化吗?
Would moving the inner function outside of this one so that its not created everytime the function is called be a micro-optimisation?
在这种特殊情况下,<$> c $ c> doMoreStuff 函数仅在 doStuff
中使用。我是否应该担心像这样的本地函数?
In this particular case the doMoreStuff
function is only used inside doStuff
. Should I worry about having local functions like these?
function doStuff() {
var doMoreStuff = function(val) {
// do some stuff
}
// do something
for (var i = 0; i < list.length; i++) {
doMoreStuff(list[i]);
for (var j = 0; j < list[i].children.length; j++) {
doMoreStuff(list[i].children[j]);
}
}
// do some other stuff
}
一个例子就是说:
function sendDataToServer(data) {
var callback = function(incoming) {
// handle incoming
}
ajaxCall("url", data, callback);
}
推荐答案
不确定如果属于微优化类别。我会说不。
Not sure if this falls under the category "micro-optimization". I would say no.
但这取决于您拨打 doStuff
的频率。如果你经常调用它,那么一遍又一遍地创建函数是不必要的,肯定会增加开销。
But it depends on how often you call doStuff
. If you call it often, then creating the function over and over again is just unnecessary and will definitely add overhead.
如果你不想拥有辅助函数 在全局范围内,但避免重新创建它,你可以像这样包装它:
If you don't want to have the "helper function" in global scope but avoid recreating it, you can wrap it like so:
var doStuff = (function() {
var doMoreStuff = function(val) {
// do some stuff
}
return function() {
// do something
for (var i = 0; i < list.length; i++) {
doMoreStuff(list[i]);
}
// do some other stuff
}
}());
由于返回的函数是一个闭包,它可以访问 doMoreStuff
。请注意,外部函数立即执行((function(){...}())
)。
As the function which is returned is a closure, it has access to doMoreStuff
. Note that the outer function is immediately executed ( (function(){...}())
).
或者您创建一个包含函数引用的对象:
Or you create an object that holds references to the functions:
var stuff = {
doMoreStuff: function() {...},
doStuff: function() {...}
};
有关封装,对象创建模式和其他的更多信息概念可以在 JavaScript这本书中找到模式 。
这篇关于没有本地功能微观优化?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!