Hi,
there’s some info out there about when to use lists vs tuples, and I get that, but nothing I’ve found talks about the efficiency of one vs the other in relation pattern matching.
I’m using card games (specifically bridge) for my explorations of Elixir, and at one point I had a hand as a list of lists, and then I thought, well, there are never going to be more than four suits, so perhaps that should be a tuple of lists, so I changed to that.
I now get to the point where I want the hand as a flat list, and thought, maybe I should have stayed with list of lists, so I created a version doing that.
The core of the difference is in this :-
Tuple version
def split(card = {0,}, {cl,di,he,sp}), do: {slot(card, cl),di,he,sp}
def split(card = {1,}, {cl,di,he,sp}), do: {cl,slot(card, di),he,sp}
def split(card = {2,}, {cl,di,he,sp}), do: {cl,di,slot(card, he),sp}
def split(card = {3,}, {cl,di,he,sp}), do: {cl,di,he,slot(card, sp)}
List Version
def split(card = {0,}, [cl,di,he,sp]), do: [slot(card, cl),di,he,sp]
def split(card = {1,}, [cl,di,he,sp]), do: [cl,slot(card, di),he,sp]
def split(card = {2,}, [cl,di,he,sp]), do: [cl,di,slot(card, he),sp]
def split(card = {3,}, [cl,di,he,sp]), do: [cl,di,he,slot(card, sp)]
From my testing, the tuple version is about 2% more efficient.
Average of 4 runs of generating 1_000_000 hands
Tuple = 47.851
List = 48.906
t sort of makes sense without knowing why … but, can anyone explain specifically why the tuple version is quicker?
Jonathan.
PS
I do remember thinking it was pretty cool to be able to pattern match INTO a list beyond head|tail when I discovered you could.