En bref. Le coût d’une allocation tient à sa fréquence. Ne le devine pas : compte-le.
Le modèle en une phrase
Chaque littéral
"…",[]ou{}alloue un objet et le GC paie pour le libérer : on ne lit pas ce coût, on le compte.
In short. An allocation’s cost lies in its frequency. Don’t guess it: count it.
The model in one sentence
Each
"…",[]or{}literal allocates an object and the GC pays to free it: you don’t read this cost, you count it.
1000.times { "abc" }1000.times { [] } ; { {} }42 :sym "abc".freeze
1000.times { "abc" }— Un littéral"abc"alloue un nouvel objet à chaque tour : environ 1000 pour 1000 tours.A"abc"literal allocates a new object every turn: about 1000 for 1000 turns.1000.times { [] } ; { {} }—[]et{}font pareil : un objet par tour.[]and{}do the same: one object per turn.42 :sym "abc".freeze— Entiers, symboles et chaîne gelée ne coûtent aucune allocation.Integers, symbols and a frozen string cost no allocation.
La preuve, avec Ruby 3.4
def alloc
avant = GC.stat(:total_allocated_objects)
yield
GC.stat(:total_allocated_objects) - avant
end
p alloc { 1000.times { "abc" } } # => 1002 (≈ 1000)
p alloc { 1000.times { "abc".freeze } } # => 0
p alloc { 1000.times { [] } } # => 1000
p alloc { 1000.times { {} } } # => 1000
p alloc { 1000.times { 42 } } # => 0
p alloc { 1000.times { :sym } } # => 0
p alloc { 1000.times { |i| i.to_s } } # => 1000Le petit écart (1002) vient du bloc de mesure lui-même, pas du littéral.
Ce que l’image cache
Un littéral isolé ne coûte presque rien : ce qui pèse, c’est un objet par tour d’une boucle chaude. Et freeze n’est pas un réflexe : geler à l’aveugle change le comportement (un FrozenError à la première mutation). Compte d’abord, gèle ensuite là où ça paie.
Pour aller plus loin
Le numéro ci-dessous détaille GC.stat, ObjectSpace et memory_profiler, avec des exercices.
The proof, with Ruby 3.4
def alloc
before = GC.stat(:total_allocated_objects)
yield
GC.stat(:total_allocated_objects) - before
end
p alloc { 1000.times { "abc" } } # => 1002 (≈ 1000)
p alloc { 1000.times { "abc".freeze } } # => 0
p alloc { 1000.times { [] } } # => 1000
p alloc { 1000.times { {} } } # => 1000
p alloc { 1000.times { 42 } } # => 0
p alloc { 1000.times { :sym } } # => 0
p alloc { 1000.times { |i| i.to_s } } # => 1000The small gap (1002) comes from the measuring block itself, not the literal.
What the picture hides
A lone literal costs almost nothing: what weighs is one object per turn of a hot loop. And freeze isn’t a reflex: freezing blindly changes behavior (a FrozenError on the first mutation). Count first, freeze where it pays.
Go deeper
The issue below details GC.stat, ObjectSpace and memory_profiler, with exercises.