Hommer Smith
Hommer Smith

Reputation: 27862

Why accessing size of tuple in Elixir is fast?

I've read in many places that finding the size of a tuple in Elixir is really fast because tuples are stored in contiguous memory cells. However, for lists is more expensive to do because one needs to traverse the whole list to know the length of the list.

I don't understand how by being in contiguous memory cells, finding out the size of a tuple will be faster. Don't you have to go through each cell too?

Upvotes: 1

Views: 311

Answers (1)

Aleksei Matiushkin
Aleksei Matiushkin

Reputation: 121010

The tuple size is stored. The length of the list is not.

A tuple is also a boxed value, so it consists of a Boxed pointer (1 word) to an ARITYVAL header (1 word), after which appear the elements of the tuple.
The arity part of the ARITYVAL header is a 26-bit (on a 32-bit system) integer value containing the number of elements in the tuple.
— https://blog.edfine.io/blog/2016/06/28/erlang-data-representation/

Upvotes: 4

Related Questions