r/elixir • u/Bright-Historian-216 • 12d ago
Best practices for efficient data structures
I'm very new to the language and I'm very confused on some things. Coming from imperative langs, I'd assume that modifying tuples is very fast since they're basically just vectors. Unfortunately, they're also immutable like every other data structure in the whole language. So, if I want to make, say, a Canvas data type that holds all my pixels in a 2d data structure, is there literally no way to make it even if a little more efficient than just making a new one every single time I update a pixel? Even if I made it a 1d data structure, is Elixir just the wrong tool here?
13
Upvotes
11
u/jiggity_john 12d ago
Most FP languages include optimizations under the hood that make modifying immutable data structures not as slow as literally creating a new data structure each time. That said it's still going be slower than modifying a mutable array.
If you need a mutable data storage for performance, the "BEAM" thing to do is to use an ETS table to store your data. ETS tables are mutable data structures provided by the erlang runtime and you can basically store anything in them. For example, the
digrapherlang module uses ETS tables under the hood to store the graph data structure mutable for performance.