Allocations cachées et GC : le modèle mental pour compter plutôt que craindre en Ruby Hidden allocations and the GC: the mental model of counting rather than fearing in Ruby

Chaque littéral alloue un objet et le GC paie pour le libérer. Le coût est dans la fréquence : on le compte avec GC.stat, on ne le devine pas. Ruby 3.4.Each literal allocates an object and the GC pays to free it. The cost is in the frequency: count it with GC.stat, don't guess. Ruby 3.4.

AuteurAuthor
Ludovic Cleuet
ThèmeTopic
PerformancePerformance
PubliéPublished

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
Compter les allocationsCounting allocations≈ 1000 objets≈ 1000 objets"abc"1000objets alloués sur 1000 tours (GC.stat[:total_allocated_objects])objects allocated over 1000 turns (GC.stat[:total_allocated_objects])vérifié avec Ruby 3.4checked with Ruby 3.4
  1. 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.
  2. 1000.times { [] } ; { {} } — [] et {} font pareil : un objet par tour.[] and {} do the same: one object per turn.
  3. 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.
Chaque littéral alloue un objet et le GC paie pour le libérer. Le coût est dans la fréquence, pas dans le littéral isolé : on ne le lit pas, on le compte avec GC.stat.Each literal allocates an object and the GC pays to free it. The cost is in the frequency, not the lone literal: you don't read it, you count it with GC.stat.

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 } }     # => 1000

Le 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 } }     # => 1000

The 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.

Questions fréquentesFrequently asked questions

Un littéral de chaîne alloue-t-il un objet à chaque évaluation ?Does a string literal allocate an object on every evaluation?

Oui par défaut : 1000.times { "abc" } alloue environ 1000 objets en Ruby 3.4. Les entiers et symboles, eux, n'allouent rien.Yes by default: 1000.times { "abc" } allocates about 1000 objects in Ruby 3.4. Integers and symbols allocate nothing.

Comment mesurer les allocations ?How do I measure allocations?

Avec GC.stat(:total_allocated_objects) avant et après un bloc, ou ObjectSpace et memory_profiler pour le détail par ligne.With GC.stat(:total_allocated_objects) before and after a block, or ObjectSpace and memory_profiler for per-line detail.

Quel est le coût d'un seul littéral ?What does a single literal cost?

Négligeable. Le coût est dans la fréquence : un objet par tour de boucle chaude pèse, le même sur un chemin froid ne pèse pas.Negligible. The cost is in the frequency: one object per hot-loop turn matters, the same on a cold path doesn't.

freeze supprime-t-il l'allocation ?Does freeze remove the allocation?

Sur un littéral, oui : 1000.times { "abc".freeze } alloue 0 objet, car le même objet gelé est réutilisé. Mais ne gèle pas à l'aveugle.On a literal, yes: 1000.times { "abc".freeze } allocates 0 objects, since the same frozen object is reused. But don't freeze blindly.

[] et {} allouent-ils aussi ?Do [] and {} allocate too?

Oui, un objet par évaluation : 1000 pour 1000 tours, comme une chaîne non gelée. i.to_s sur un entier alloue lui aussi une chaîne.Yes, one object per evaluation: 1000 for 1000 turns, like an unfrozen string. i.to_s on an integer allocates a string too.

RubyGCAllocationsPerformanceModèle mental

← Tous les articlesAll articles