Home
2022-11-07
Elixir Data Structures and Memory
Lists v. Tuples
Tuples
are placed in contiguous memory slots and behave like static data structures. they are not meant to change.
- meant for single data points that have a fixed number of elements
- memory usage is static and allocated upfront
- does NOT support insertion or deletion. any change requires a complete copy
iex(1)> tuple = {false, 1, 2, 3, false}
# use cases - key/value pair mappings
iex(3)> a = {:name, "Mark"}
iex(4)> b = {:rank, :general}
# which lends itself to Keyword lists
# in Elixir, Keyword Lists are syntactic sugar for a List
# with Tuples. so this:
iex(5)> kw_list = [name: "Mark", rank: :general]
# equals this:
iex(6)> list = [{:name, "Mark"}, {:rank, :general}]
# verify it with:
iex(7)> Enum.at(list, 0)
# => {:name, "Mark"}
how would this look in memory?
Lists
specifically in Elixir, are implemented as linked lists and are used to hold variable-length data. distributed arbitrarily, in no particular order, with each element holding a reference to the next one:
- supports insertion/deletion
- O(n) linear time
- fetching can be slow
iex(2)> list = [false, 1, 2, 3, false]
Links and Resources
How Elixir Lays Out Your Data in Memory - honeybadger