En bref. Une chaîne stricte pousse tout à chaque maillon ; lazy attend qu’on tire.
Le modèle en une phrase
lazyne calcule rien tant qu’on ne tire pas : les éléments descendent la chaîne un à un, et on s’arrête dès qu’on en a assez.
In short. A strict chain pushes everything through each link; lazy waits to be pulled.
The model in one sentence
lazycomputes nothing until you pull: elements flow down the chain one by one, and it stops as soon as there are enough.
(1..10).map { _1 * 2 }.select { _1 % 3 == 0 }.first(3)
(1..10).map { _1 * 2 }— Strict :maptraite les dix éléments et matérialise un tableau.Strict:mapprocesses all ten elements and builds an array..select { _1 % 3 == 0 }.first(3)— On n'en voulait que trois, mais les dix sont déjà calculés :[6, 12, 18].We only wanted three, but all ten are already computed:[6, 12, 18].
La preuve, avec Ruby 3.4
seen = []
r = (1..Float::INFINITY).lazy
.map { seen << _1; _1 * 2 }
.select { _1 % 3 == 0 }
.first(3)
p r # => [6, 12, 18]
p seen # => [1, 2, 3, 4, 5, 6, 7, 8, 9]Sur l’infini, neuf éléments seulement ont été touchés. En strict sur (1..10), les dix le sont, pour le même résultat.
L’Enumerator, dessous
e = [10, 20, 30].each
p e.next, e.peek, e.next, e.next # => 10, 20, 20, 30
e.nextStopIteration: iteration reached an endEt on fabrique sa propre suite infinie :
fib = Enumerator.new { |y| a, b = 0, 1; loop { y << a; a, b = b, a + b } }
p fib.take(8) # => [0, 1, 1, 2, 3, 5, 8, 13]
p fib.lazy.select(&:even?).first(4) # => [0, 2, 8, 34]Ce que l’image cache
lazy n’est pas gratuit : chaque élément traverse des appels de bloc supplémentaires. Sur dix éléments, l’overhead dépasse le gain ; il paie sur de grandes ou infinies séquences, ou quand on sort tôt.
Pour aller plus loin
Le numéro ci-dessous détaille lazy et les Enumerator (next, peek, Enumerator.new), avec des exercices.
The proof, with Ruby 3.4
seen = []
r = (1..Float::INFINITY).lazy
.map { seen << _1; _1 * 2 }
.select { _1 % 3 == 0 }
.first(3)
p r # => [6, 12, 18]
p seen # => [1, 2, 3, 4, 5, 6, 7, 8, 9]On infinity, only nine elements were touched. Strict on (1..10) touches all ten, for the same result.
The Enumerator, underneath
e = [10, 20, 30].each
p e.next, e.peek, e.next, e.next # => 10, 20, 20, 30
e.nextStopIteration: iteration reached an endAnd you can build your own infinite sequence:
fib = Enumerator.new { |y| a, b = 0, 1; loop { y << a; a, b = b, a + b } }
p fib.take(8) # => [0, 1, 1, 2, 3, 5, 8, 13]
p fib.lazy.select(&:even?).first(4) # => [0, 2, 8, 34]What the picture hides
lazy isn’t free: each element goes through extra block calls. On ten elements, the overhead exceeds the gain; it pays off on large or infinite sequences, or when you exit early.
Go deeper
The issue below details lazy and Enumerator (next, peek, Enumerator.new), with exercises.