In lesson 132 every object got a slot on the heap. A String keeps its characters in its slot; an ordinary object keeps its instance variables there – one VALUE after the other, behind the header. Only the values, though: there is no room for names. So where does Ruby write down that @x is the first value and @y the second? Not in the object – a thousand Dots would carry the same list a thousand times. Not in the class either – two objects of one class can have different instance variables. Since Ruby 3.2 the answer is a shape. ObjectSpace.dump shows it:
require "objspace"
require "json"
class Dot
def initialize(x, y)
@x = x
@y = y
end
end
JSON.parse(ObjectSpace.dump(Dot.new(1, 2)))Two "ivars", and "embedded" => true: they sit in the 24-byte slot itself, right behind the header. And "shape_id", a number. It names a node in a tree that Ruby keeps for the whole program, the shape tree. Its root, shape 0, means "no instance variables". Every other node has a parent and one name: from the root, the edge @x leads to the shape "@x in slot 0"; from there, @y leads to "@x in slot 0, @y in slot 1". Setting a new instance variable moves an object one step down the tree – and if that step was ever taken before, by any object of any class, Ruby reuses the node it made then. Some objects compared (the numbers differ from run to run; what counts is which ones are equal):
dump = ->(obj) { JSON.parse(ObjectSpace.dump(obj)) }
shape_of = ->(obj) { dump.(obj)["shape_id"] }
# another class, the same names in the same order
class Blip
def initialize
@x = 0
@y = 0
end
end
# the same names, the other way round
class Tod
def initialize
@y = 0
@x = 0
end
end
before = RubyVM.stat(:next_shape_id)
dots = Array.new(1000) { |i| Dot.new(i, i) }
{
"new shapes for 1000 Dots" => RubyVM.stat(:next_shape_id) - before,
"shapes of the Dots" => dots.map(&shape_of).uniq,
"Blip" => shape_of.(Blip.new),
"Tod" => shape_of.(Tod.new),
"Object.new" => shape_of.(Object.new),
"after object_id" => shape_of.(Object.new.tap(&:object_id)),
}A thousand Dots, one shape – and not a single new shape was made for them. Blip is another class, but it set the same names in the same order, so it shares Dot's shape. Tod set @y first: another path through the tree, another shape, although its objects hold the same two names. A plain Object.new sits at the root, 0. After object_id it is at 1: in Ruby 4.0 an object keeps its id, once asked for, in a hidden field next to its instance variables, and that is a step in the tree too – to shape 1, which is reserved for it.
A 24-byte slot has room for three instance variables. Where do six go?
class Roomy
def initialize
@a, @b, @c, @d, @e, @f = 1, 2, 3, 4, 5, 6
end
end
class Sprawl
def fill
@a, @b, @c, @d, @e, @f = 1, 2, 3, 4, 5, 6
self
end
end
slot = ->(obj) { dump.(obj).values_at("slot_size", "embedded", "shape_id") }
{
"Roomy" => slot.(Roomy.new),
"Sprawl, first" => slot.(Sprawl.new.fill),
"Sprawl, second" => slot.(Sprawl.new.fill),
}Roomy's very first object got a 48-byte slot with room for all six. When Ruby ran def initialize, it counted the instance variables the method sets and noted 6 in the class; Roomy.new asks for a slot that big. Sprawl sets its variables in another method, so its first object got the smallest slot, and when the fourth variable did not fit, they all moved out into memory from malloc. "embedded" is nil: the object is extended, and every access goes one pointer further. But the class learned from the shape how big its objects grow, and the second Sprawl got a big slot. (Run the cell again: now the first one does too. On a 64-bit laptop the slots are 40 and 80 bytes.) All three show the same shape_id: the dump prints only the node in the tree. Inside, Ruby keeps the slot size in three more bits of the same number.
Why shapes make Ruby fast
In lesson 129 you read instructions. Reading @weight is one, too: getinstancevariable :@weight, <is:0>. Its second operand is the instruction's own inline cache, a little memory in the instruction sequence that holds one shape id and one slot index. Each time it runs, the instruction compares the object's shape id with the cached one. Equal – a hit – and the value is in that slot: one comparison, one read. Not equal – a miss – and Ruby walks up the tree from the object's shape to the node for @weight, takes its index and writes the new pair into the cache. (setinstancevariable caches the shape after its step and checks that the object stands there already or one step above it.) Packet sets @fragile only when it is true, a common pattern. The cell prints the instruction, then plays the cache with the real shape ids of packets:
class Packet
def initialize(weight, fragile = false)
@fragile = true if fragile
@weight = weight
end
def weight = @weight
end
puts RubyVM::InstructionSequence.of(Packet.instance_method(:weight)).disasm
# a model of <is:0>: it remembers one shape
cache = ->(objects) do
cached = nil
objects.map do |obj|
shape = shape_of.(obj)
hit = shape == cached
cached = shape # a miss fills the cache
hit ? :hit : :miss
end.tally
end
mixed = Array.new(10) { |i| Packet.new(i, i.odd?) }
plain = Array.new(10) { |i| Packet.new(i) }
{ "mixed" => cache.(mixed), "plain" => cache.(plain) }Fragile and plain packets in turn: ten misses. A fragile Packet has @weight in slot 1 under one shape, a plain one has it in slot 0 under another, and a cache that holds one pair is always wrong. Ten plain packets: one miss, then nine hits – and since the real cache keeps its pair from call to call, a program that only makes plain packets hits every time. The cure is dull: set every instance variable in initialize, always, in the same order – @fragile = fragile instead of @fragile = true if fragile. A false costs one slot; a second shape costs a miss at every place that reads the variable.
Too many shapes
A class whose objects keep taking new paths would fill the tree. So Ruby counts, for each class, its variations: each time one of its objects adds a branch to a node that already had one. At 8 – SHAPE_MAX_VARIATIONS – the class gets no new shapes at all. An object that would need one becomes too complex: its instance variables move into a hash table, and reading them is a hash lookup that no cache can skip. With Warning[:performance] = true, Ruby says when it happens. Bag takes its names from a Hash, like code that turns JSON or a config file into objects:
class Bag
def initialize(fields)
fields.each { |name, value| instance_variable_set("@#{name}", value) }
end
end
Warning[:performance] = true
# show the warning below the cell
old_stderr, $stderr = $stderr, $stdout
bags = Array.new(12) { |i| Bag.new("f#{i}" => i, "z" => 0) }
$stderr = old_stderr
Warning[:performance] = false
bags.map { |bag| dump.(bag).values_at("shape_id", "too_complex_shape") }Seven Bags got shapes of their own. The first name of each, @f0, @f1 …, branched off at the root, which had children from earlier lessons already: a variation every time. With the eighth Bag the count reached 8, and the warning came. The eighth still got @f7 and fell at @z; every Bag after it that needs a new shape is too complex from the start: "too_complex_shape" => true, and as its shape_id the dump shows the root's 0. Those Bags still work – bags.last.instance_variable_get(:@z) gives 0 – only slower. (A second run prints no warning: the variations have been counted already.)
- A node of the tree:
struct rb_shape:79–edgesto its children,edge_name,parent_id,next_field_index. Shapes 0 and 1 are fixed:ROOT_SHAPE_ID:72. - One step down:
rb_shape_transition_add_ivar:937callsshape_get_next:804, andget_next_shape_internal:594looks inedgesfirst – it makes a new child only when none is there. The way back up, as in the model:shape_get_iv_index:778. - The instructions:
getinstancevariable:209andsetinstancevariable:222in insns.def; the cache's one comparison:vm_getivar:1312in vm_insnhelper.c. - The slot size:
def initializecounts the variables (vm_insnhelper.c:6039,rb_estimate_iv_count:2984),newallocates for them:rb_class_allocate_instance:118. The bits of a shape id:shape.h:22; the dump keeps only the node:objspace_dump.c:419. - Too many:
SHAPE_MAX_VARIATIONS:67; the counting and the warning:shape.c:833; into the hash table:obj_transition_too_complex:1559in variable.c.
ruby -W:performance yourscript.rb turns on the performance warnings for a whole program, the shape warning among them. ObjectSpace.dump_all writes every object on the heap, each with its shape_id, as JSON lines into a file.transition(shape, ivar) gives back the child of shape with one more instance variable – and, as in Ruby, the same node every time it is asked for the same step, so that objects built in the same order end up at the same node. index_of(shape, ivar) gives the slot of ivar in an object of that shape, or nil: walk up the parents until a node's ivar is the one you are looking for. The check builds real objects in different orders and compares: two orders must give the same node in your tree exactly when Ruby gives them the same shape_id.class ShapeNode
attr_reader :id, :parent, :ivar, :index, :edges
def initialize(id, parent, ivar)
@id = id
@parent = parent
@ivar = ivar
@index = parent ? parent.index + 1 : -1
@edges = {}
end
end
class ShapeTree
attr_reader :root
def initialize
@root = ShapeNode.new(0, nil, nil)
@next_id = 1
end
def shape_for(ivars)
ivars.reduce(root) { |shape, ivar| transition(shape, ivar) }
end
# the child of shape with one more ivar: the same node every time
def transition(shape, ivar)
node = ShapeNode.new(@next_id, shape, ivar)
@next_id += 1
node
end
# the slot of ivar in an object of this shape: walk up towards the root
def index_of(shape, ivar)
nil
end
end
tree = ShapeTree.new
xy = tree.shape_for([:@x, :@y])
[xy.equal?(tree.shape_for([:@x, :@y])), tree.index_of(xy, :@y)]