[erlang-questions] optimal way to append an element in a list inside a map

Dmitry Kolesnikov dmkolesnikov@REDACTED
Tue Aug 29 20:19:54 CEST 2017


Hello,

Premature optimisation is an evil ;-)

I would use the following syntax:
```
append(Key, Value, Map) ->
   List = case Map of
      #{Key := Tail} -> 
         [Value | Tail];
      _ ->
         [Value]
   end,
   Map#{Key => List}.
```

Lists are not copied they are referenced. Maps… Hmm, I am not sure. I hope the implementation is smart enough to keep reference as well.

- Dmitry


> On 29 Aug 2017, at 20.34, Caragea Silviu <silviu.cpp@REDACTED> wrote:
> 
> Hello,
> 
> Having a map where the value of each element it's a list :
> 
> #{ 1 => [], 2 => [], ... n => []} 
> 
> and you need to append elements in the list for a specific key, what's the most optimal way to do this without copying the lists and the map inside the VM lot of times ?
> 
> Anything better than the following solution:
> 
> append_element(Key, Value, Map) ->
>     case maps:find(Key, Map) of
>         {ok, V} ->
>             maps:put(Key, [Value | V], Map);
>         _ ->
>             maps:put(Key, [Value], Map)
>     end.
> 
> Kind regards,
> Silviu
> _______________________________________________
> erlang-questions mailing list
> erlang-questions@REDACTED
> http://erlang.org/mailman/listinfo/erlang-questions




More information about the erlang-questions mailing list