Duplicating values in maps: are terms actually copied?

Let’s say I have a function that modifies a struct by duplicating the value for a key to a different key.

A simplified example:

defmodule MyPlugParser do
  use Plug.Builder

  plug Plug.Parsers, parsers: [:json], json_decoder: Poison

  # When decoding JSON with root-level arrays, Poison will merge
  # the array in the params using a "_json" key.
  # This extracts the list and moves it into the assigns.
  #
  def call(conn, opts) do
    conn = super(conn, opts)
    my_data_list = conn.params["_json"]
    assign(conn, :my_data_list, my_data_list)
  end
end

Is the term stored in conn.params["_json"] actually copied in memory? Or does it just use a reference to the same data? It’s a potentially long list, so copying it would not be ideal.

Would it be different for other data types?

The nice thing with persistent data structures is that copying is unnecessary for things that don’t change. If the list doesn’t change, then the list isn’t copied. Creating more things that reference the list won’t copy the list.

This is true of all data types.

7 Likes

Thank you, makes sense.