Three ways to measure memory in Ruby
Memory is easy to talk about and hard to measure. The first decision is not which gem to install. It is which number you actually need.
Ask two developers how much memory a Ruby process uses and you may get two different answers, both correct. One is describing the operating system view: how many pages are resident. The other is describing the heap view: how many bytes the program has asked for. They are related, but they are not the same question.
Before reaching for a profiler, decide which budget you are trying to protect. That choice narrows the tools considerably.
Budget one: resident size
The resident set is the amount of physical memory the operating system has given to the process. It is what a container limit cares about. The cheapest way to read it is to ask the system about the current process, or to inspect the process table from outside. The number includes more than the Ruby heap: shared libraries, the interpreter, and memory that has been freed but not yet returned all show up here.
Resident size is a good alarm, not a good explanation. If it grows without bound, something is wrong. If it stays flat, you still do not know whether the program is allocating efficiently.
Budget two: allocated bytes
Allocation tracing records objects as they are created. This is the number that answers the question "how much churn is this block producing?" It is excellent for tests, because a small change in a hot path can produce a large change in temporary objects. It is less useful in production, because the tracing itself costs memory and time.
| Measure | Answers | Cost |
|---|---|---|
| Resident set | What is the system holding right now? | Very low |
| Allocated bytes | How much did this block create? | Moderate to high |
| Retained objects | What is still alive after the work? | High |
Budget three: retained objects
An allocation count tells you about traffic. A retention count tells you about residents. If a block allocates a million small objects and drops them immediately, that is a throughput problem. If it allocates ten objects and keeps them forever, that is a leak. The two problems need different fixes.
Measure the number that matches the failure you are afraid of. Everything else is trivia with a nicer graph.
A workable habit
For everyday code, start with resident size as a smoke alarm and allocation tracing in tests for hot paths. Reach for retention analysis only when memory grows across repeated runs. Run a full collection before taking a baseline, keep the sampling window short, and write down which number you measured. A benchmark without a noun is just a number in a costume.
The Ruby ecosystem has several good tools for the third budget. They are worth learning, but they are not the first step. The first step is deciding what you mean by memory.