I wondered if using prototypes in JavaScript should be more memory efficient than binding every element of an object to it for the following reasons:
- A prototype is just one object.
- The copies contain only references to their prototype.
Versus:
- Each instance contains a copy of all elements and methods that are defined by the constructor.
I started experimenting a bit 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 creates a random string of length x.
Then I created the objects in large quantities as follows:
var arr = new Array(); for (var i = 0; i < 1000; i++) { arr.push(new TestObjectFat());
and checked the memory usage in the browser (Google Chrome). I know that is not very accurate ...
However, in both cases, memory usage increased significantly, as expected (about 30 MB for TestObjectFat ), but the prototype version did not use much less memory (about 26 MB for TestObjectThin ).
I also verified that the TestObjectThin instances contain the same string in the "text" property, so they really use the prototype property.
Now I'm not very sure what to think about it. Prototyping doesn't seem to be a great screensaver.
I know that prototyping is a great idea for many other reasons, but I specifically deal with memory usage here. Any explanation why the prototype variant uses almost the same amount of memory? Did I miss something?
javascript memory-management inheritance prototype
selfawaresoup
source share