Make Internals Behave Predictably

Two things in our applications can randomly slow it down: GC and system calls. (I/O is the most common case of a system call.)

I can imaging you sighing, “Oh no, not GC again.” But in this case it’s easy to neutralize its effect on measurements, in one of two ways.

First, it’s sometimes OK to disable GC completely before measurement. If raw performance of our code is what we’re interested in, then it’s absolutely fine to do that.

If we want our measurement to be closer to the real world, we can try to make GC as predictable as possible by forcing it before executing the code, like this:

 
GC.start
 
measurement = Benchmark.realtime ​do
 
...
 
end

This way our code will trigger GC in the same manner ...

Get Ruby Performance Optimization now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.