[erlang-questions] Cost of Copy

Johan Montelius johanmon@REDACTED
Fri May 28 15:09:11 CEST 2010


On Fri, 28 May 2010 12:46:50 +0200, Richard Andrews  
<bflatmaj7th@REDACTED> wrote:

> IIRC, if A is not used in the code after X is bound, the erlang
> compiler can optimise this to an in-place operation where the storage
> for A is reused for X. So only the B element pointer is changed to
> point to B' and no allocation is required. Is this not one of the
> reasons for record syntax?

I would be happily surprised if that is the case. Determining if A is the  
last reference to the structure involves either a lot of program analysis  
or run-time reference counting. The record syntax solves a problem of  
readability, maintainability etc of src code.

To see why the compiler will have a hard time identifying when it is safe  
to do destructive updates look at the following:


foo(X) ->
	case X of
		{A, B, C} ->
			B1 = mod(B),
			Y = {A, mod(B), C}
			zot(Y)
	end.


If X is the last reference to the structure {A, B, C} we can replace B  
with B1 and just hand it to zot/1. The problem is of course that we don't  
know if X is used somewhere else. If this was the call to foo/1


     :
   foo(X),
   bar(X),
     :

then we would make a mistake in destroying the structure.  To figure out  
at compile time when it is safe to reclaim structures is tricky.

  Johan





-- 
Associate Professor Johan Montelius
Royal Institute of Technology - KTH
School of Information and Communication Technology - ICT


More information about the erlang-questions mailing list