Prototypal inheritance should save memory, right?

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()); // or new TestObjectThin() } 

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?

+6
javascript memory-management inheritance prototype
source share
2 answers

Your test is suspicious - there is significant overhead when distributing JavaScript objects, which probably distorts your results. If you insert large drops of data into your prototype class, it may have a larger gain.

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

+2
source share

In both cases, you created 1000 objects, and the object in memory is much heavier than a string. Thin vs Fat represents a win of 999 lines. So let's say that creating an object (even a simple one) costs 26 thousand, and creating 1000 lines of whole lines costs 4 thousand. Then your remark is perfectly explained.

 Fat = 1000 * 26Ko + 1000 * 4Ko = 30Mo Thin = 1000 * 26Ko + 4Ko = 26Mo 
+1
source share

All Articles