Optimizing Ruby’s Memory Layout: Variable Width Allocation
Ruby 3.2's Variable Width Allocation replaces CRuby's single 40-byte RVALUE slot with five size pools (40, 80, 160, 320 and 640 bytes) so classes, strings, arrays and objects can store their data adjacent to the object instead of in separate malloc'd memory. Heap pages grew from 16 KB to 64 KB, and compaction moves resized objects into the best-fitting pool to restore data locality. Embedded strings now go up to 615 bytes and arrays and objects up to 78 elements or instance variables. Microbenchmarks show up to 35% speedups and railsbench gains 2.1%. The change also adds GC.stat_heap, offers a build flag to disable the feature, and opens the door to MMTk-based garbage collector research.
Related posts
- Year in Review 2022: Tenderlove's Ruby and Rails Reflections and Predictions
Shopify Engineering easyNoviceRuby's 2022 highlights include YJIT's rewrite in Rust and its new ARM support, so `ruby --yjit` now runs on Apple Silicon development machines as well as production. Variable Width Allocation became the default: Ruby learns when a class needs more instance-variable slots than the fixed 40-byte object provides and allocates later instances from wider slot pools, which improves cache locality. Ruby 3.2's Object Shapes give inline caches a class-independent key based on which instance variables were set and in what order, which helps deep hierarchies like Active Record. On the tooling side, Ruby LSP brings editor features to Ruby, and Error Highlight's column-level error pointers now appear on Rails error pages, part of a broader push for developer ergonomics in 2023.
- Adventures in Garbage Collection: Improving GC Performance in our Massive Monolith
Shopify Engineering hardMasterShopify cut Ruby garbage-collection tail latency in its monolith by finding why major GCs were triggered, via GC.latest_gc_info(:major_by), and removing each cause in turn. Major marks took over 4 seconds, and most were triggered by the oldmalloc limit, so the team effectively disabled it. They then preallocated slots per size pool for Ruby 3.2's variable width allocation, since deploys every 30 minutes kept processes in warm-up. They also added write barriers to Ruby core types and gems, cutting shady objects from about 160,000 to about 3,000. Finally, out-of-band major GC every 128–512 requests cut p99.9/p99.99 GC time by about 10x and nearly eliminated GC pauses for median requests, with the warning never to tune GC without first measuring the impact.
- The effect of switching to TCMalloc on RocksDB memory use
Cloudflare mediumAdeptQuicksilver's memory roughly doubled after its storage moved to RocksDB, climbing from about 15GB to 30GB over several days. Heap profiling showed the heap was about a third of RSS, which pointed to the allocator rather than a leak. glibc malloc gives threads independent per-thread arenas (60-80 arenas for about 25 threads), and memory cannot move between them, so fragmentation multiplies. Mitigations such as MALLOC_ARENA_MAX, periodic malloc_trim and M_MMAP_THRESHOLD each cost lock contention or syscalls, while TCMalloc's middle-end moves freed memory between per-core caches and cut memory use by 2.5x.
- Code Ranges: A Deeper Look at Ruby Strings
Shopify Engineering hardMasterRuby strings are mutable and encoding-aware across 100+ encodings, so runtimes cache a per-string "code range" (UNKNOWN, 7BIT, VALID, BROKEN) to avoid repeated O(n) validity scans. In MRI and JRuby the value occupies two bits in the object header and is mutually exclusive rather than a true bitmask, so combining masks yields confusing bugs. MRI avoids rescans by computing code ranges lazily and by deriving result code ranges from operation semantics (e.g. 7BIT stays 7BIT, single-byte-optimizable strings). TruffleRuby instead computes them eagerly and stores them on rope nodes, amortizing the cost through rope reuse and deriving results without byte scans.
- A Database Without Dynamic Memory Allocation
TigerBeetle mediumAdeptTigerBeetle allocates all memory once at startup and never again, using fixed limits for connections, in-flight messages per client, replicas, message size and queries per message so that total memory is a simple compile-time sum. Beyond avoiding GC and use-after-free, static allocation bounds overload, makes resource use predictable for operators, and lets assertions on pool availability surface sizing mistakes under fuzzing rather than as production resource exhaustion. Supporting choices include fixed-size, cache-line-aligned 128-byte account and transfer structs sent zero-copy over the wire, batched queries (up to 8191 per message), and an LSM forest whose in-memory portion is preallocated and kept bounded by small incremental flushes to disk.