Lazy and eager
Lazy and eager are two answers to one question: when does the work happen? An Enum call does it now and hands back a list; a Stream call in Elixir describes it and does nothing until something asks. This page is about the choice between them, and about the two places a stream surprises a reader: the work it repeats, and the endless source it makes possible.
The same result two ways
Most pipelines can be written with either module, and the answers are equal. The eager version builds a list after every step, and the lazy one builds one list at the end; for five numbers neither is better, and for a million the difference is memory:
same.exs
list = 1..5 eager = list |> Enum.map(&(&1 * 2)) |> Enum.filter(&(&1 > 4)) lazy = list |> Stream.map(&(&1 * 2)) |> Stream.filter(&(&1 > 4)) |> Enum.to_list() IO.inspect(eager) IO.inspect(lazy) IO.inspect(eager == lazy)
elixir same.exs
[6, 8, 10]
[6, 8, 10]
true
The eager version writes less and needs no last call, which is why it is the right default. The lazy version earns its place when the input is large, when the source never ends, or when the pipeline may stop before the end.
An endless stream that ends
Stream.iterate/2 builds 1, 2, 3 and so on forever, and Stream.take_while/2 ends the pipeline at the first item that fails its test. Enum.find/2 ends a cyclical stream at the first match, which is a search that cannot be written over a list:
endless.exs
squares = Stream.iterate(1, &(&1 + 1)) |> Stream.map(&(&1 * &1)) |> Stream.take_while(&(&1 < 100)) |> Enum.to_list() IO.inspect(squares) IO.inspect(Stream.cycle([1, 2, 3]) |> Enum.find(&(&1 == 2)))
elixir endless.exs
[1, 4, 9, 16, 25, 36, 49, 64, 81]
2
The squares stop at 81 because 100 is the first square that is not below 100: the pipeline computes ten values and stops, not infinitely many. The second line is the same idea with Enum.find/2, which stops at the first match and never asks for another item.
What a Stream costs
Each step of a stream is a closure, and each item is passed from one closure to the next, so a stream pipeline does more work per item than the same chain of Enum calls. The trade is memory against calls: the stream never holds a list, and the eager chain holds one after every step. On a small list that the program needs whole, the eager chain is both shorter and faster, and a stream adds a layer with no benefit. A page of a course cannot show a timing, because the number changes with every run and machine; the rule is the one above, and the program is the one that reads best.
The mistake: the stream the program enumerates twice
A stream is a recipe and not a cache. Every Enum call runs the recipe again, so a stream that is stored and consumed twice does its work twice, side effects included:
twice.exs
stream = Stream.map([1, 2, 3], fn n -> IO.puts("map #{n}") n * 2 end) IO.inspect(Enum.to_list(stream)) IO.inspect(Enum.to_list(stream))
elixir twice.exs
map 1
map 2
map 3
[2, 4, 6]
map 1
map 2
map 3
[2, 4, 6]
A program that reads a file as a stream and then consumes it twice reads the file twice, and a program that logs inside the stream logs twice. The fix is to consume it once and keep the list, or to build a new stream for the second use. The printed pairs of lines are the evidence: the same three map lines appear under each list.
The programs on this page were run with Elixir 1.19.7 on Erlang/OTP 27 (erts 15.2.7.14), on Linux x86_64 in a Docker container.
Questions
A new set of questions in a new order every time. Choose one answer for each, then check.
-
Which module is the lazy one?
Answer
Stream
Stream builds the description of the work; an Enum call is what runs it.
-
What does a stream do when it is enumerated a second time?
Answer
It runs the whole pipeline again
A stream is a recipe; each Enum call cooks it again, side effects included.
-
Which call ends a pipeline over an endless stream?
Answer
Stream.take_while/2
take_while asks for items until the first one fails its test, so the source is never exhausted.
-
When is the eager Enum chain the better choice?
Answer
When the input is small and the whole result is needed
For a small result the stream adds per-item cost and no benefit.
-
What does this program print?
IO.inspect(Stream.iterate(1, &(&1 + 1)) |> Stream.take_while(&(&1 < 4)) |> Enum.to_list())Answer
[1, 2, 3]
The pipeline stops at 4, the first value that is not below 4.
-
What does this program print?
IO.inspect(1..4 |> Stream.map(&(&1 * 2)) |> Enum.to_list())Answer
[2, 4, 6, 8]
The stream doubles each item and the Enum call collects the four results.
-
What does this program print?
IO.inspect(Stream.cycle([:a, :b]) |> Enum.take(5))Answer
[:a, :b, :a, :b, :a]
The cycle repeats both atoms and take asks for five values.
-
What does this program print?
IO.inspect(Stream.cycle([1, 2, 3]) |> Enum.find(&(&1 == 3)))Answer
3
find stops at the first matching value and never asks for another cycle.
-
What is the cost of a stream step per item?
Answer
a closure call between the steps
Each item travels through the closures of the steps, which costs a call per step per item.
-
What keeps a program from hanging on
Stream.iterate/2?Answer
a final Enum call with a limit such as take or take_while
The source never ends, so the pipeline needs a step that stops asking for values.
Article author: Arthur Isaev