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:
Versus:
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 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?
Prototypical inheritance allows us to reuse the properties or methods from one JavaScript object to another through a reference pointer function.
By now you must have realized the difference between classical inheritance and prototypal inheritance. Classical inheritance is limited to classes inheriting from other classes. However prototypal inheritance includes not only prototypes inheriting from other prototypes but also objects inheriting from prototypes.
Here we can say that " animal is the prototype of rabbit " or " rabbit prototypically inherits from animal ". So if animal has a lot of useful properties and methods, then they become automatically available in rabbit . Such properties are called “inherited”.
Both classical and prototypal inheritance are object-oriented programming paradigms. Objects in object-oriented programming are abstractions that encapsulate the properties of an entity.
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).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With