匿名功能和内存消耗 [英] Anonymous functions and memory consumption

查看:77
本文介绍了匿名功能和内存消耗的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在内存消耗方面,它们是否相等,或者我们是否为后者中的每个对象都获得了新的函数实例?

  var f = function(){alert(this.animal);} 
var items = [];
for(var i = 0; i <10; ++ i)
{
var item = {animal:monkey};
item.alertAnimal = f;
items.push(item);
}

  var items = []; 
for(var i = 0; i <10; ++ i)
{
var item = {animal:monkey};
item.alertAnimal = function(){alert(this.animal);};
items.push(item);
}

编辑

我在想,为了让关闭正常工作,第二个实例确实会创建一个新的函数。这是正确的吗?

解决方案

您应该查看第一个方法,因为第二个方法在每次解释器传递该行时创建一个函数。

关于你的编辑:我们一直在同一个范围内,因为JavaScript有函数范围而不是块范围,所以这个可能可以优化,但我没有遇到不会每次都创建它的实现。我建议不要依赖这个(可能的话)优化,因为如果你广泛使用这种技术,那么缺乏支持的实现可能会超出内存限制(这很糟糕,因为你不知道什么实现会运行它,对吗?)。

In terms of memory consumption, are these equivalent or do we get a new function instance for every object in the latter?

var f=function(){alert(this.animal);}
var items=[];
for(var i=0;i<10;++i)
{
    var item={"animal":"monkey"};
    item.alertAnimal=f;
    items.push(item);
}

and

var items=[];
for(var i=0;i<10;++i)
{
    var item={"animal":"monkey"};
    item.alertAnimal=function(){alert(this.animal);};
    items.push(item);
}

EDIT

I'm thinking that in order for closure to work correctly, the second instance would indeed create a new function each pass. Is this correct?

解决方案

You should pefer the first method, since the second one creates a function every time the interpreter passes that line.

Regarding your edit: We are in the same scope all the time, since JavaScript has function scope instead of block scope, so this might be optimizable, but i did not encounter an implementation that doesn't create it every time. I would recommend not to rely on this (probably possible) optimization, since implementations that lack support could likely exceed memory limits if you use this technique extensively (which is bad, since you do not know what implementation will run it, right?).

这篇关于匿名功能和内存消耗的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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