How come Elixir requires less memory when it doesn't mutate variables?

I am new to functional programming and learning Elixir now. I have 2 silly questions.

  1. If everytime Elixir makes a new copy when a variable is changed why doesn’t it require a lot of memory , irl it’s exactly opposite. What is the underlying mechanism here?

  2. On IEX

a = 1
a = 2

Isn’t this mutating variable a ?

1 Like
  1. It doesn’t need to make a copy that often. For example if you add to the front of a list, you can just create 1 element in memory and set the next element pointer to point to the old list. That way the old list doesn’t need to be copied. If you update one key in a map, the other keys can still point to the same data as the old map, because the data cannot be changed.
  2. That’s rebinding the variable a. It now points to a new piece of data but the original data is not changed. Example:
a = %{foo: 1}
b = a # Now a and b point to the same data

a = %{a | foo: 2}

# %{foo: 2}

# %{foo: 1}
# b was not changed even though the value in a was updated. A new copy was made for a.

Aha Thanks!

1 Like

1.) Elixir uses persistent data structures.

2.) Personally I avoid talking about variables in Elixir altogether (I refer to them as names - I also avoid talking about statements as Elixir uses expressions; there is no return keyword for functions because expressions always have to evaluate to a value).