NamedTuples vs Dict

I wondered about use cases of NamedTuples vs Dicts.
Obviously one would choose a NamedTuple if the order of elements is important and a Dict if the keys have to be something else than a symbol, but are there any other situations where one is preferred over the other?

5 Likes

Small NamedTuples are much cheaper to construct than small Dicts:

julia> @btime (a=1, b=2)
  1.753 ns (0 allocations: 0 bytes)

julia> @btime Dict(:a => 1, :b => 2)
  102.756 ns (4 allocations: 608 bytes)

But on the other hand, NamedTuples cannot be changed after they are constructed, while you can add, delete, or change elements in a Dict easily.

So NamedTuples are great when you want to construct them very quickly and don’t need to modify the result after you create it, while Dicts are great when you want to create a mapping that you can update in the future.

12 Likes

Also, if you care about the order of the elements but you still want a mutable container, then check out OrderedDict from DataStructures.jl.

3 Likes

NamedTuple encodes it’s structure in the type, Dict encodes that in the value so every trade off between runtime and compile time computation applies here just like countless number of other cases in the language. It’s basically the same as choosing between Tuple and Array.

13 Likes