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).
Following up on this comment, here's what you should do: Try to produce a memory problem - Write code that creates all these objects and graudally increase the upper limit until you ran into a problem (Browser crash, Browser freeze or an Out-Of-memory error). Ideally you should repeat this experiment with different browsers and different operating system.
Now there are two options: option 1 - You didn't succeed in producing the memory problem. Hence, you are worrying for nothing. You don't have a memory issue and your program is fine.
option 2- you did get a memory problem. Now ask yourself whether the limit at which the problem occurred is reasonable (in other words: is it likely that this amount of objects will be created at normal use of your code). If the answer is 'No' then you're fine. Otherwise you now know how many objects your code can create. Rework the algorithm such that it does not breach this limit.
I believe you forgot to include 'array'.
I have re-factored the code in my original answer. I have removed the recursion and removed the assumed existence overhead.
Having the same problem. I searched on Google and I want to share with stackoverflow community this solution.
Important:
What do you think about it?
Chrome developer tools has this functionality. I found this article very helpful and does exactly what you want: https://developers.google.com/chrome-developer-tools/docs/heap-profiling
Sometimes I use this to flag really big objects that might be going to the client from the server. It doesn't represent the in memory footprint. It just gets you approximately what it'd cost to send it, or store it.
Also note, it's slow, dev only. But for getting an ballpark answer with one line of code it's been useful for me.