Abdelhamid
Abdelhamid

Reputation: 1

Erlang memory variables management

we consider this Erlang example :

X1=[1,2,4,6....we consider there are 10 millions element],
X2=[2,6,5,2,...we consider there  are 100 millions element],
X3=.......
. 
. 

X10000=.....

this code will allocate spaces for billions of elements so let's try this :

L=[X1, X2,....., X10000]. 

in Java "X1, X2,..." are just references toward memory allocations so this code in Java will allocate memory for the values of these variables and assign to the variables the memory's adresses to reference toward this values, so when we create the list L and we call X1.... the variables reference to the precedent allocation of memory and we have allocate memory just one time.

if we consider that "=" is an expression and not an assignement between a variable and a memory adress (thay what Joe said in his book) variables X1,.... X10000 in the L list will be allocated in memory for the second time ?

Upvotes: 1

Views: 175

Answers (1)

Alexey Romanov
Alexey Romanov

Reputation: 170745

From the book you were already recommended on a previous question, section 12.4.1:

Objects on the heap are passed by references within the context of one process. If you call one function with a tuple as an argument, then only a tagged reference to that tuple is passed to the called function. When you build new terms you will also only use references to sub terms.

L=[X1,...]

is building a new term, so it only uses references to X1 etc. and allocates enough new memory to make a list; it doesn't copy the lists referred to by X1 etc.

In both cases the list members are passed by reference. Now if you have

X1 = [1,2],
L = [X1, X1]

the situation is more interesting (but still explained by that quote); there are not two copies of [1, 2] in memory like there would be in

L = [[1, 2], [1, 2]]

instead both members of L point to the same list.

Fundamentally, Erlang allocates memory for values, not for variables, unlike C and its descendants including Java; a variable doesn't really correspond to a memory address.

Upvotes: 3

Related Questions