2

How does the memory management of variables work in Elixir and Erlang?

Is it pass-by-reference? Pass-by-value? Something else?

Adam Millerchip
  • 20,844
  • 5
  • 51
  • 74
  • 2
    An answer to this question might be found in literally each and every tutorial. – Aleksei Matiushkin Jul 13 '22 at 03:49
  • Because there is no way to observe whether a function changes a variable, no one knows. As for memory management, erlang uses garbage collection. – 7stud Jul 13 '22 at 04:45
  • 4
    See e.g. [this answer](https://stackoverflow.com/a/39996506/3457068). – pottu Jul 13 '22 at 07:13
  • 5
    Here's another answer: https://erlang.org/pipermail/erlang-questions/2013-March/072760.html – legoscia Jul 13 '22 at 07:54
  • 3
    More details here: https://hamidreza-s.github.io/erlang%20garbage%20collection%20memory%20layout%20soft%20realtime/2015/08/24/erlang-garbage-collection-details-and-why-it-matters.html – legoscia Jul 13 '22 at 08:09
  • 3
    [Here](https://stackoverflow.com/questions/40480/is-java-pass-by-reference-or-pass-by-value)'s an equivalent Java question that has over 7000 upvotes and 2 million views. I think this question is on-topic and the down and close votes are unwarranted. – Adam Millerchip Jul 14 '22 at 02:37

1 Answers1

2

Elixir always passes COPIES of the variable's value; Elixir never passes variables by reference. Passing by reference is impossible in Elixir even if you wanted to (unless I'm woefully mistaken). This strategy is partly what makes Elixir particularly well suited for dealing with issues of concurrency.

Everett
  • 8,746
  • 5
  • 35
  • 49
  • 1
    I assume one should make a difference between the concept and the implementation. Conceptually, Elixir always passes values. But I assume there are several optimisations to avoid the physical copy when possible (for instance when the compiler knows that the function won't modify the variable). – bortzmeyer Jul 13 '22 at 15:31
  • Yes, for data structures it will typically only make physical copies when crossing the process boundary, as explained in the [link](https://stackoverflow.com/questions/39996344/does-elixir-makes-a-copy-of-a-map-when-passed-as-an-function-argument/39996506#39996506) in a comment above. – sabiwara Jul 13 '22 at 23:11
  • You can see it with the following: `list = [1, 2, 3];` `fun = & &1;` `fun2 = &(Task.async(fn -> &1 end) |> Task.await());` `true = :erts_debug.same(list, fun.(list));` `false = :erts_debug.same(list, fun2.(list))` – sabiwara Jul 13 '22 at 23:12