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?