Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does elixir makes a copy of a map when passed as an function argument?

Tags:

elixir

In other words , I'm wondering whether in elixir a map is passed to a function by value or by reference. I suspect it is by value given Elixir's principle of no side effect. But then wouldn't a large map create huge duplication inefficiency?

Thanks in advance for your help.

like image 655
shivakumar Avatar asked Oct 12 '16 10:10

shivakumar


1 Answers

Since all terms in Elixir are immutable, there's no difference to the user whether the argument is passed "by value" or "by reference". You can never modify the value of a term in a function and have that reflected in the variable the caller sent to the function. Maps specifically could be considered to be passed "by reference", in that only a pointer to them is sent to the function by the VM, which is very efficient.

One thing to note is that terms passed to other processes are deep copied by the VM. The only exception to this is "large" Strings, usually > 64 bytes, which are passed as a reference to a global binary heap, and use reference counting for garbage collection.

I suspect it is by value given Elixir's principle of no side effect.

Elixir is not pure, it has side effects. For example, you can add I/O to any function. You probably meant no mutable values.

like image 51
Dogbert Avatar answered Sep 22 '22 21:09

Dogbert