Martin Kristiansen
Martin Kristiansen

Reputation: 10222

How are records stored in erlang, and how are they mutated?

I recently came across some code that looked something like the following:

-record(my_rec, {f0, f1, f2...... f711}).

update_field({f0, Val}, R) -> R#my_rec{f0 = Val};
update_field({f1, Val}, R) -> R#my_rec{f1 = Val};
update_field({f2, Val}, R) -> R#my_rec{f2 = Val};
....
update_field({f711, Val}, R) -> R#my_rec{f711 = Val}.

generate_record_from_proplist(Props)->
    lists:foldl(fun update_field/2, #my_rec{}, Props).

My question is about what actually happens to the record - lets say the record has 711 fields and I'm generating it from a proplist - since the record is immutable, we are, at least semantically, generating a new full record one every step in the foldr - making what looks like a function that would be linear in the length of the arguments, into one that is actually quadratic in the length, since there are updates corresponding to the length the record for every insert - Am I correct in this assumption,or is the compiler intelligent enough to save me?

Upvotes: 1

Views: 210

Answers (2)

Pascal
Pascal

Reputation: 14042

Records are tuples which first element contains the name of the records, and the next one the record fields.

The name of the fields is not stored, it is a facility for the compiler, and of course the programmer. I think it was introduced only to avoid errors in the field order when writting programs, and to allow tupple extension when releasing new version without rewriting all pattern matches.

Your code will make 712 copies of a 713 element tuple.

Upvotes: 2

tkowal
tkowal

Reputation: 9289

I am afraid, the compiler is not smart enough. You can read more in this SO answer. If you have so big number of fields and you want to update it in O(1) time, you should use ETS tables.

Upvotes: 2

Related Questions