当分配给函数中声明的变量并分配给较大范围内的变量时,我对执行速度的显着差异感到有些困惑。
我写了一个小小的测量函数,我在这些事情的全局范围内,这里有一些结果:
Chrome(控制台)
measure("assignment to var in current scope", function(){
var i = 1;
(function(){})(i)
})
15:52:49 |INFO| Measure 'assignment to var in current scope' performed 76236944 operations per second
iterations: 10000000 duration: 141 totalcalllag: 9.83
......并在上方范围内
var i = 0;
measure("assignment to var in upper scope", function(){
i = 1;
(function(){})(i)
})
15:53:22 |INFO| Measure 'assignment to var in upper scope' performed 2935124 operations per second
iterations: 10000000 duration: 3417 totalcalllag: 9.99
7600 ops / sec用于范围分配,而 300万 ops / sec用于在上限范围内分配〜 1:25 !
IE11(控制台)
measure("assignment to var in current scope", function(){
var i = 1;
(function(){})(i)
})
15:54:14|INFO| Measure 'assignment to var in current scope' performed 46038396 operations per second
iterations: 10000000 duration: 247 totalcalllag: 29.790000000000002
var i = 0;
measure("assignment to var in upper scope", function(){
i = 1;
(function(){})(i)})
8669267
15:54:49 |INFO| Measure 'assignment to var in upper scope' performed 8669267 operations per second
iterations: 10000000 duration: 1183 totalcalllag: 29.5
在这里,我们看到 4600万,而非 850万每秒操作。
衡量功能
var measure = function (desc, f) {
// measure the calling code first
var start, stop, callLag, nothing = function () {
};
var iterations = 0;
var COUNT = 1000;
var duration = 0;
while (duration < 10) {
COUNT *= 1000;
start = (new Date()).getTime();
while (iterations != COUNT) {
++iterations;
nothing();
}
stop = (new Date()).getTime();
duration = stop - start;
}
callLag = duration / COUNT;
// measure for total time between 0.1 & 10 seconds
iterations = 0;
COUNT = 1000;
duration = 0;
while (duration < 100) {
COUNT *= 100;
start = (new Date()).getTime();
while (iterations != COUNT) {
++iterations;
f();
}
stop = (new Date()).getTime();
duration = stop - start;
}
// calculate operations per second
var opsPerSec = Math.floor(1000 * (iterations / (duration - (callLag * iterations))));
Log.info("Measure '" + desc + "' performed " + opsPerSec.toString() + " operations per second\n" +
"\titerations: " + iterations + "\tduration: " + duration + "\ttotalcalllag: " + callLag*iterations);
return opsPerSec;
};
问题
我将很快用JavaScript进行一些繁重的数字运算。所有浏览器的这种行为是否一致?我应该考虑到这一点来实现功能吗?我应该在内部将参数传递给函数以避免在较高范围内访问它们吗?
......或者我错过了什么?
答案 0 :(得分:0)
理论上它不应该对JavaScript有任何影响。变量声明在JavaScript方面非常重要,因为语言只有function scope
(与阻止范围相反)。我总是遵循JavaScript大师Douglas Crockford(Javascript:The Good Parts的作者)给出的建议。
JavaScript does not have block scope, so defining variables in blocks can confuse programmers who are experienced with other C family languages. Define all variables at the top of the function.
请在以下网址阅读更多详情:Variable Declarations
我还建议使用Crockford JSLint: The JavaScript Code Quality Tool他也发出警告:JSLint will hurt your feelings