liveBook · Manning

Deep copy

As explained in Elixir in Action, Third Edition

A deep copy is a recursive copy of a value that duplicates the complete hierarchy of nested terms rather than sharing its mutable parts.

A deep copy recursively duplicates a value’s complete hierarchy, so processes can exchange data without sharing memory. In BEAM, sending a message or closing over a variable for a spawned process copies the relevant terms. section 5.2.1 section 5.4.3

Treat deep copying as an operational boundary with practical performance consequences:

  • Preserves process isolation: the receiving process cannot directly alter the sender’s internal data. section 5.4.3
  • Copies nested structures in memory; occasional large messages may be acceptable, while frequent transfers of complex data can reduce performance. section 5.4.3
  • Uses reference copying for binaries larger than 64 bytes, literals, and terms created through :persistent_term. section 5.4.3
  • Returns snapshots when data crosses an ETS boundary, even though ETS tables themselves are mutable and shared among processes. section 10.3.1

Passing data into a spawned process

A closure such as spawn(fn -> some_fun(data) end) deep-copies data into the new process. Likewise, send(target_pid, data) copies the message contents, allowing the processes to continue independently. section 5.4.3

data = ...
 
spawn(fn ->
  ...
  some_fun(data)      #1
  ...
end)

Inspect how a value captured by a spawned function crosses the process boundary. section 5.4.3

How Elixir in Action, Third Edition covers it

How deep it goes
Explains message and closure copying, performance trade-offs, reference exceptions, and ETS snapshots without detailing the copy algorithm.
Examples
Uses spawned closures, process messages, and ETS reads and writes as concrete copying boundaries.
What it assumes
Assumes familiarity with BEAM processes, spawned functions, messages, closures, and ETS tables.
What you can do after
Evaluate data-transfer costs and isolation behavior when designing concurrent BEAM processes or using ETS.
How it connects
Connects deep copy to processes, message passing, closures, shared-nothing concurrency, ETS tables, and garbage collection.

Also explained in

Compare how 5 books explain deep copy →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Elixir in Action, Third Edition. The section links point to the parts of the book it draws on.