Javascript函数对象有多大? [英] How big are Javascript function objects?

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

问题描述

我只是想知道函数对象的开销是多少。在OOP设计模型中,您可以使用自己的私有函数生成很多对象,但是如果您有10,000多个,我认为这些私有函数对象会产生大量开销。我想知道是否有足够的情况将这些函数移动到实用程序类或外部管理器以保存这些函数对象占用的内存。

解决方案

这是Chrome处理功能的方式,其他引擎可能会做不同的事情。



让我们来看看在此代码中:

  var funcs = []; 
for(var i = 0; i< 1000; i ++){
funcs.push(function f(){
return 1;
});
}
for(var i = 0; i< 1000; i ++){
funcs [0]();
}



*)这不完全正确,它还包含范围信息,函数名称和其他元数据,这就是为什么在这种情况下它的大小为592字节。


I was just wondering how the overhead is on a function object. In an OOP design model, you can spawn up a lot of objects each with their own private functions, but in the case where you have 10,000+, these private function objects, I assume, can make for a lot of overhead. I'm wondering if there are cases where it would be advantageous enough to move these functions to a utility class or external manager to save the memory taken up by these function objects.

解决方案

This is how Chrome handles functions, and other engines may do different things.

Let's look at this code:

var funcs = [];
for (var i = 0; i < 1000; i++) {
    funcs.push(function f() {
        return 1;
    });
}
for (var i = 0; i < 1000; i++) {
    funcs[0]();
}

http://jsfiddle.net/7LS6B/4/

Now, the engine creates 1000 functions.

The individual function itself takes up almost no memory at all (36 bytes in this case), since it merely holds a pointer to a so-called SharedFunctionInfo object, which is basically a reference to the function definition in your source code*. This is called lazy parsing.

Only when you run it frequently does the JIT kick in, and creates a compiled version of the function, which requires more memory. So, funcs[0] takes up 256 bytes in the end:

*) this is not exactly true, it also holds scope information, the function's name and other metadata, which is why it has a size of 592 bytes in this case.

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

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