开发者

Prototypal inheritance should save memory, right?

I've been wondering whether using prototypes in JavaScript should be more memory efficient than attaching every member of an object directly to it for the following reasons:

  • The prototype is just one single object.
  • The instances hold only references to their prototype.

Versus:

  • Every instance holds a copy of all the members and methods that are defined by the constructor.

I started a little experiment with this:

var TestObjectFat = function()
    {
        this.number = 42;
        this.text = randomString(1000);
    }

var TestObjectThin = function()
    {
        this.number = 42;
    }
TestObjectThin.prototype.text = randomString(1000);

randomString(x) just produces a, well, random String of length x.

I then instantiated the objects in large quantities like this:

var arr = new Array();
for (var i = 0; i < 1000; i++) {
    arr.push(new TestObjectFat()); // or new TestObjectThin()
}

and checked the memory usage of the browser process (Google Chrome). I know, that's not very exact...

However, in both cases the memory usage went up significantly as expected (about 30 MB for TestObjectFat), but the prototype variant used not much less memory (about 26 MB for TestObjectThin).

I also checked that the TestObjectThin instances contain the same string in their "text" property, so they are really using the property of the prototype.

Now, I'm not so sure what to think about this. The prototyping doesn't seem to be the big memory sav开发者_StackOverflow中文版er at all.

I know that prototyping is a great idea for many other reasons, but I'm specifically concerned with memory usage here. Any explanations why the prototype variant uses almost the same amount of memory? Am I missing something?


Your test is suspect - there is a significant overhead in allocating JavaScript objects which is likely skewing your results. If you insert large blobs of data into your prototype class, it may show a larger gain.

Unfortunately memory usage is hard to control in JavaScript, especially when JIT is involved (are your JITed methods represented in the memory usage model? etc).


In both case, you created 1000 objects and an object is much heavier in memory than a string. The Thin vs Fat represents a gain of 999 strings. So let's say that creating an object (even a simple one) costs 26k, and that creating a 1000 chars wide string costs 4k. Then your observation is perfectly explained.

Fat = 1000 * 26Ko + 1000 * 4Ko = 30Mo
Thin = 1000 * 26Ko + 4Ko = 26Mo
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜