I want to know the size occupied by a JavaScript object.
Take the following function:
function Marks(){
this.maxMarks = 100;
}
function Student(){
this.firstName = "firstName";
this.lastName = "lastName";
this.marks = new Marks();
}
Now I instantiate the student
:
var stud = new Student();
so that I can do stuff like
stud.firstName = "new Firstname";
alert(stud.firstName);
stud.marks.maxMarks = 200;
etc.
Now, the stud
object will occupy some size in memory. It has some data and more objects.
How do I find out how much memory the stud
object occupies? Something like a sizeof()
in JavaScript? It would be really awesome if I could find it out in a single function call like sizeof(stud)
.
I’ve been searching the Internet for months—couldn’t find it (asked in a couple of forums—no replies).
I use Chrome dev tools' Timeline tab, instantiate increasingly large amounts of objects, and get good estimates like that. You can use html like this one below, as boilerplate, and modify it to better simulate the characteristics of your objects (number and types of properties, etc...). You may want to click the trash bit icon at the bottom of that dev tools tab, before and after a run.
Instantiating 2 million objects of just one property each (as in this code above) leads to a rough calculation of 50 bytes per object, on my Chromium, right now. Changing the code to create a random string per object adds some 30 bytes per object, etc. Hope this helps.
If your main concern is the memory usage of your Firefox extension, I suggest checking with Mozilla developers.
Mozilla provides on its wiki a list of tools to analyze memory leaks.
The Google Chrome Heap Profiler allows you to inspect object memory use.
You need to be able to locate the object in the trace which can be tricky. If you pin the object to the Window global, it is pretty easy to find from the "Containment" listing mode.
In the attached screenshot, I created an object called "testObj" on the window. I then located in the profiler (after making a recording) and it shows the full size of the object and everything in it under "retained size".
More details on the memory breakdowns.
In the above screenshot, the object shows a retained size of 60. I believe the unit is bytes here.
There is a NPM module to get object sizeof, you can install it with
npm install object-sizeof
A little late to the party, but here's a slightly more compact solution to the problem:
Sorry I could not comment, so I just continue the work from tomwrong. This enhanced version will not count object more than once, thus no infinite loop. Plus, I reckon the key of an object should be also counted, roughly.