views:

61

answers:

2

Hi Folks,

I've been wondering:

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 30MB for TestObjectFat), but the prototype variant used not much less memory (about 26MB for TestObjectThin).

I also checked: 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 saver 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?

+2  A: 

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).

Yann Ramin
I could try it with much longer strings in the object properties. Maybe that will show a difference...
Techpriester
+1  A: 

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
Alsciende
I have a hard time believing that a simple object like this uses up memory in that orders of magnitude. Are you sure about that?
Techpriester
Absolutely not. I just wanted to show that your result can be explained.
Alsciende