How to reduce memory usage in the Crystal language?

Hello.

I really like the performance of Crystal.

I recently used Valgrind and Hotspot on Linux and Instruments on macOS to investigate performance bottlenecks and learned that I can speed up the program.

I am not quite sure how to reduce memory usage though.

Do you have any recommendations?

For example, it would be great if there was a way to visualize how instances of Crystal objects are occupying memory over time during program execution in the form of Treemapping

The screenshot below is of a software called GrandPerspective for macOS.

GrandPerspective is a small utility application for macOS that graphically shows the disk usage within a file system.

I wish I could do this kind of thing not only with HDD but also with memory, although such a useful thing may not exist.

Crystal GC uses sbrk to allocate memory and valgrind doesn’t support applications that allocate memory that way :frowning:

But IIRC people already posted in this forum other workarounds to track memory usage by monkey patching some classes in stdlib.

1 Like

Maybe you are referring to perf-tools? in any case, it won’t give any visual map like the one asked here. But @kojix2 if you find a good visualizer to do that, maybe you can tweak the output of perf_tools/mem_prof to make it work.

2 Likes

You can also use Instruments to track allocations. It doesn’t have a nice view like GP and you can’t really tell what the object was, but it can quickly point you towards issues.

1 Like

Valgrind includes separate tools to track allocations and stuff. Unfortunately it doesn’t work out of the box with libgc, but perhaps it is possible to make it work somehow. At the very least it should work with GC::None, but that is more than a little bit limiting, of course.

But if someone could figure out how to make them work together by default then that would of course be optimal.

1 Like