Share this post!

Profiling Ruby’s Memory Allocation with TCmalloc

Everytime Ruby needs to request memory from the operating system it has to call the malloc function. This function is part of the operating system itself, but there are alternative implementations you can use.

One of those implementations is Google’s tcmalloc.

TCmalloc is part of the Google Performance Tools suite.

You can use these tools to explore exactly how Ruby allocates memory.

And thanks to the LD_PRELOAD environment variable (in Linux) we can replace the system malloc with tcmalloc.

Enabling The Profiler

You can enable tcmalloc’s profiler with an additional environment variable (HEAPPROFILE).

This will produce the following output:

Here you see a confirmation that the profiler has been enabled, then we see the program’s output, after that we find the filename (profile.0001.heap) & the amount of memory used by our program (2 MB).

To read this file you will need another tool included with tcmalloc.

This will produce the following output:

Well, that’s just a bunch of memory addresses! You need a version of Ruby with debugging symbols to be able to see the function names.

Then you will get this output:

What you see here is how much memory was allocated by which MRI’s functions.

It’s interesting to know that aligned_malloc is the function used to allocate new pages for Ruby objects, stack_chunk_alloc is used by the GC itself during the marking phase, and objspace_xmalloc0 / objspace_xcalloc allocate space for strings, arrays & any other data that doesn’t fit in a RVALUE struct.


TCmalloc knows nothing about Ruby objects, the only thing it does is track calls to malloc, calloc & realloc to find out how much memory is requested.

If you want to get a heap dump at the Ruby level you can use ObjectSpace.dump_all. This gives you a JSON file with all the live objects in your application & their memory size.

But what tcmalloc can show you is a visualization of all the C functions that end up requesting memory.

This will open Chrome or Firefox with an SVG file that looks like this:

ruby heap profile

Not only does TCmalloc give you this nice profiling capability, but using it you can also increase your application’s performance by 4-9%! You could also try jemalloc, which is another malloc implementation that also includes a profiler.


You have learned how to use gperftools (Google Performance Tools) to visualize & analyze the memory usage of the Ruby interpreter. If you liked this I think you will also enjoy my upcoming book on Ruby internals 🙂

Thanks for reading!

Leave a Comment: