How much garbage is my JavaScript producing?

While reading this article about garbage collection in JavaScript, a question popped up in my head… How can I test how much garbage a piece of code is producing?

I’ve written a small snippet that can measure this for you. What you need is a recent version of Google Chrome.

To be able to measure the memory heap size, we need to enable it in Chrome. Chrome can give you access to the state of the JavaScript heap (the memory allocated to JavaScript objects), but to get it to work you’ll need to start it with the –enable-precise-memory-info flag:

This will write the number of bytes allocated between "// Start" and "// End" to console every 10th of a second.

My current version of Chrome (40.0.2214.115) is producing 40 bytes to run this function, that is why I remove 40 bytes from the output number. You may need to change this depending on your Chrome version and settings.

If you run this script, you will notice that the first output numbers are

2424
728
0
0
0
...

The first numbers are there probably because of initialization garbage. After a little while, the initialization garbage is gone and we see that the number of allocated bytes in the loop is 0.

Now, let's allocate something in the loop and see what happens. If I, for example, allocate a plain object inside the above loop, like this,