Ryan Peschel
Ryan Peschel

Reputation: 11976

How to track memory allocations in Javascript / Chrome?

Apparently a lot of questions have been asked about this but I cannot find the answer, so if this is indeed a duplicate please close this and redirect me to the answer.

I am developing a browser game and am trying to keep allocations to a minimum, by using pre-allocated arrays, not returning objects, avoiding language functions that allocate, using numbers wherever possible, etc.

Despite this, my memory graph in Chrome after doing a 10 second performance recording looks like this:

enter image description here

My question is simple: how can I find out what is causing allocation every frame? Surely there is a better way than just doing a text search on the codebase for the "known suspects" like new, returning objects from functions, creating new arrays, etc.

Ideally I would also be able to determine what is causing the most allocations and contributing the most to those spikes and sawtooths, so I can start with the low-hanging fruit first. Is this possible?

Upvotes: 6

Views: 1303

Answers (1)

yurish
yurish

Reputation: 919

Chrome developer tools provide more options for memory profiling under memory tab.

Aside from the quick memory snapshots more people are familiar with, you can also run recordings of two different types. Allocation sampling for a simple approximate overview of memory allocations per function (collected throughout the recording), and allocation instrumentation, which will give you a timeline to inspect allocations over time. Don't forget to check "Record stack traces of allocations" (since that's what you're initially looking for), then you'll find stack traces that lead to the creation of a selected object in the bottom panel under "Allocation stack" tab.

Looking at the graph I expect you won't see any allocation spikes on the timeline, heap growth rate seems pretty constant. The spikes could be due to the rate of garbage collection and sawtooths are either the tick rate of your game (in case your game has a synchronous central loop) or the sampling rate of the profiler. Just something to take into account. There still may be room for some memory optimization.

Upvotes: 3

Related Questions