Performance Implications of Immutability

It would be easy to assume that this approach to programming is inefficient. After all, you have to create a new copy of data whenever you update it, and that’s going to leave lots of old values around to be garbage-collected. Let’s look at these in turn.

Copying Data

Although common sense might dictate that all this copying of data is inefficient, the reverse is true. Because Elixir knows that existing data is immutable, it can reuse it, in part or as a whole, when building new structures.

Consider this code. (It uses a new operator, [ head | tail ], which builds a new list with head as its first element and tail as the rest. We’ll spend a whole chapter on this when we talk about lists and recursion. ...

Get Programming Elixir 1.3 now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.