Elixir Map vs Erlang :array

It appears that the Elixir Map implementation is mostly an ergonomic wrapper for :maps in Erlang. In many graph/network exercises I’ve been faced with the need to convert a structure of List of Lists to something accessible by index. I have been mostly doing this by

list 
|> Enum.map(fn row -> row |> Enum.with_index() |> Enum.map(fn {n, i} -> {i, n} end) |> Map.into() end)
|> Enum.with_index() 
|> Enum.map(fn {v, k} -> {k, v} end) 
|> Map.new()

So that I end up with %{0 => %{0 => n_0 ... n => n_n } ... } that I can access with graph[row][col].
Would Erlang arrays be a more efficient structure for repeated access? I’m assuming more than 32 elements, so the large map vs small map distinction is not the determining factor. In my mind Maps were lists of two-tuples but I’m not sure that’s right, at least for large maps. Arrays seem to be implemented as tuples of n-tuples. My instinct is that arrays would be more efficient at write functions but maps more efficient at read/access functions. Am I on the right track? Any tips on setting up a benchmark?

Not only library, but also the benchmarks:

5 Likes

You should also try %{{0, 0} => value} that is accessed graph[{row, col}]. I have a feeling this is faster since it’s one lookup not two.

4 Likes

One minor code-golf: anytime you see Enum.map |> Map.new/1 you can use Map.new/2 instead.

I doubt there’s a material performance difference (it’s still :maps.from_list/1 ultimately building the output) but it’s definitely less characters :stuck_out_tongue:

4 Likes

@hauleth Brilliant, thanks. Looking at the graphs in the benchmark section of the library’s readme I’m not sure I understand the conclusions in the corresponding text about the ErlangArray vs MapArray implementations. For instance:
image
To me the different implementations seem identical at sizes >8k according to the graph. In any case they seem to be close enough to equivalent for my purposes. I’m glad someone has already put this work in.

@benwilson512 Thanks for the tip. You are right of course about the efficiency, but the tradeoff would be n lookups for n length rows if I ever wanted to deal with things by row. It also is just easier for me to keep it visualized in my head.

@al2o3cr That’s a good tip. Thanks.

1 Like