HerokuRichard SchneemanExplainer
The Life-Changing Magic of Tidying Ruby Object Allocations
Summary
The post presents object-allocation profiling as a way to find Ruby performance hotspots, including code inside libraries such as Active Record. It uses memory_profiler and derailed_benchmarks to group allocations by gem, file, and source location, then examines whether each allocation can be removed or avoided. A benchmark compares a direct maximum comparison with an array-based version: the array allocation makes the latter 2.04x slower in the reported run. One optimization for cache_version reuses a raw database timestamp string when it is safe, checking its type, format, timezone, and provenance before deleting separators and padding PostgreSQL-truncated values. This change reduces allocation from 743,842 bytes and 6,626 objects to 702,955 bytes and 6,063 objects, and the post reports up to 1.12x faster; combined optimizations reach 1.23x overall.
Context
The work addresses slow applications by focusing on memory allocations as a source of performance hotspots. The examples use a real-world application and include allocations originating in Rails libraries.
Approach / What changed
The post uses memory_profiler and derailed_benchmarks to identify allocation hotspots by file and line, then benchmarks and refactors code to avoid unnecessary objects. One change conditionally transforms a raw database timestamp string in place for fast cache-version generation.
Takeaways
The reported array-allocation benchmark is 2.04x slower than a direct comparison of two values.
The cache_version fast path requires a String timestamp, :usec formatting, UTC timezone, and a value that did not come from the user.
The cache_version change cuts allocation by 40,887 bytes and 563 objects, while the post reports up to 1.12x faster performance; combined optimizations reach 1.23x.
Source and freshness
- Source
- heroku.com
- Published
- Added to Yomu
Summaries are generated from the original by a language model. Check the original before relying on it.
Keep reading
Related reading
The Good Stuff
Paid picks we use ourselves. Links carry a referral code — a subscription through one earns us a commission at no extra cost to you.
The best engineering reads, once a week
One useful email. Unsubscribe anytime.