In Ruby, what is stored on the stack? In Ruby, what is stored on the stack? ruby ruby

In Ruby, what is stored on the stack?


It depends on the Ruby implementation.

For example, Ruby 2.0 MRI (the typical one on most systems) stores all its objects in heaps. Small objects such as short strings can fit entirely in the heaps. For large objects, Ruby will malloc extra memory outside of the heaps.

See "MRI Memory Allocation - A Primer For Developers" and "Demystifying the Ruby GC"

Here's "Understanding How Ruby Stores Objects In Memory" which has a great, longer, description:

"The entire space that an object takes up in memory is not stored inside the Slot. Rather each Slot is a small fixed size space which can be thought of as the Ruby interpreter's handle a location in memory. This location exists outside of the Ruby Heap itself and contains the real 'meat' of the object. To be clear, if you have a 50MB string - the 50MB of data is stored outside of Ruby's Heap. If you really want to know the story of the 50MB, the space for it is actually allocated by something like the malloc command in C (as good ol' Ruby is written in C) and then stored on the System Heap. The Slot in the Ruby Heap simply contains a reference to that memory location on the System Heap which contains the 50MB of data."

"Ruby has it's own heap management which actually consists of several 'Ruby Heaps' to manage objects created during the execution of a Ruby program; this is separate from the System Heap for your Operating System. Each individual Ruby Heap contains Slots, with each Slot able to one reference one object.

Another good source is "How Ruby Manages Memory and Garbage Collection", which links to slides at "Garbage Collection Slides from LA Ruby Conference".

"As a garbage collected language, Ruby takes the easy route by putting everything on the heap".

Fibers

Fibers are special in Ruby because each fiber gets its own small stack.

"As opposed to other stackless light weight concurrency models, each fiber comes with a small 4KB stack. This enables the fiber to be paused from deeply nested function calls within the fiber block."

You may be interested in a long-running feature request for dynamic fiber stack sizing.

If you are more interested in a real-world solution, the feature request author recommends this workaround: "refactor the operation which requires a large stack to run in a separate thread and then block on thread.value."

You can also consider compiling a custom version of Ruby with your own choices for FIBER_MACHINE_STACK_ALLOCATION_SIZE and FIBER_VM_STACK_SIZE in the cont.c source file. That file also shows how fiber stacks are allocated, freed, etc.