在JavaScript中,在循环内创建函数可能会造成计算上的浪费的具体原因有哪些? [英] In JavaScript, what are specific reasons why creating functions within a loop can be computationally wasteful?

查看:84
本文介绍了在JavaScript中,在循环内创建函数可能会造成计算上的浪费的具体原因有哪些?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在JavaScript中,在循环内创建函数可能会造成计算上的浪费的具体原因是什么?

In JavaScript, what are specific reasons why creating functions within a loop can be computationally wasteful?

在JavaScript的好部分的第39页上,道格拉斯·克罗克福德(Douglas Crockford)指出:避免在循环中创建函数.这可能在计算上是浪费的".我似乎无法弄清楚为什么在循环中创建函数比在外部创建函数还要浪费.

On page 39 of JavaScript the Good Parts, Douglas Crockford states, "Avoid creating functions within a loop. It can be computationally wasteful". I can't seem to figure out why creating functions within a loop would be anymore wasteful than outside.

推荐答案

因为您要创建多个Function对象,而不是仅重用一个对象.

Because you're creating several Function objects instead of reusing just one.

创建相同功能的示例...

Example of creating an identical function...

for (var i = 0; i < 10; i++) {
    // v--creating identical function in each iteration.
    (function(j) {
        var el = document.createElement('a');
        el.onclick = function() { alert(j); };
        document.body.appendChild(el);
    })(i);
}

重用命名函数的示例...

Example of reusing a named function...

for (var i = 0; i < 10; i++) {
    var el = document.createElement('a');
      // ----------v---calling a reusable function
    el.onclick = createHandler(i);
    document.body.appendChild(el);
}

function createHandler(j) {
    return function() { alert(j); };
}

两个示例具有相同的结果,但是第二个示例不需要在循环过程中创建两个函数的开销.相反,它仅创建一个处理程序.

The two examples have the same outcome, but the second doesn't require the overhead of making two functions during the loop. Instead it creates just the one handler.

这篇关于在JavaScript中,在循环内创建函数可能会造成计算上的浪费的具体原因有哪些?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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