[erlang-questions] Arrays and setelement

Bjorn Gustavsson <>
Thu Jan 4 17:02:50 CET 2007

Mikael Pettersson <> writes:

> --===============2110319572==
> On Fri, 29 Dec 2006 03:11:19 +0000, Joel Reymont wrote:
> >> setelement works by copying, except when the BEAM compiler
> >> can prove that intermediate copies are redundant, in which
> >> cases it simple performs assignments.

There is an additional constraint: the tuple must not have been
garbage collected so that it is in the old generation heap, becase
that could create a pointer from the old generation heap to the
youngest generation heap (which the garbage collector cannot handle).

> The BEAM compiler uses this to optimise tuple and record
> initialisation. It may or may not be able to do it in more
> general cases; Björn Gustavsson should be able to tell us that.

Because of the constraint mentioned above, the compiler only optimizes
setelement calls in a straight block of code ("basic block") to be
sure that the tuple being modified is in the youngest generation.

Furthermore, the first argument for setelement/3 (the Index argument)
must be a literal index for the optimization to place.

Therefore, the second call to setelement/3 will be replaced with the
cheaper "destructive setelement instruction" in this code

set(T0) ->
    T = setelement(3, T0, a),
    setelement(2, T, b).

but not in this code

set(I, J, T0) ->
    T = setelement(I, T0, a),
    setelement(J, T, b).


Björn Gustavsson, Erlang/OTP, Ericsson AB

More information about the erlang-questions mailing list