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:
chrome --enable-precise-memory-info
Or, on OSX:
open -a "Google Chrome" --args --enable-precise-memory-info
Now, create an HTML file containing the following code.
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,
setInterval(function(){
var before = window.performance.memory.usedJSHeapSize;
var obj = new Object();
var diff = window.performance.memory.usedJSHeapSize - before;
console.log(diff-40);
}, 100);
then the output is
3360
752
56
56
56
56
...
We conclude that a plain JavaScript object takes 56 bytes to allocate.
You can use this code snippet to measure how much GC load different pieces of code allocates in your game loop. Why not try this JSFiddle here to get started? Good luck!