Does erlang implement record copy-and-modify in any clever way?

后端 未结 4 836
盖世英雄少女心
盖世英雄少女心 2021-02-10 09:13

given:

-record(foo, {a, b, c}).

I do something like this:

Thing = #foo{a={1,2}, b={3,4}, c={5,6}},
Thing1 = Thing#foo{a={7,8}}.         


        
4条回答
  •  无人共我
    2021-02-10 09:30

    In conclusion:

    Thing = #foo{a={1,2}, b={3,4}, c={5,6}},
    Thing1 = Thing#foo{a={7,8}}.
    

    Here, if Thing is not used again, it will probably be updated in place and copying of the tuple will be avoided, as the Efficiency Guide says. (tuple and record syntax is complied into something like setelement, I think)

    Thing = #ridiculously_large_record,
    Thing1 = make_modified_copy(Thing),
    Thing2 = make_modified_copy(Thing1),
    ...
    

    Here the tuples are actually copied every time.

    I guess that it would be theoretically possible make an interesting optimization to this. If the compiler could perform escape analysis on the return value of make_modified_copy and detect that the only reference to it is the one returned, in could save this information about the function. When it encounter a call the that function it would know that it is safe to modify the return value in place.

    This would only be possible to do on inter module calls, because of the code replace feature.

    Maybe one day we will have it.

提交回复
热议问题