Reputation: 510
If I have a list of Key Value tuples e.g. List = [{key1, value1}, {key2, value2}] is it better to use
lists:keyfind(Key, N, TupleList) e.g. lists:keyfind(key1, 1, List)
to find a given value or
dict:from_list(List)
to turn it into a dict and then lookup with dict:fetch/2 or dict:find/2 ?
Using a dict is more readable for me as it returns the value directly so I can use it inline, however I was wondering which was more efficient?
Thanks.
Upvotes: 1
Views: 1119
Reputation: 176
You also have the option to use proplists:lookup(), part of the stdlib and pragmatically would be the most idiomatic way to express what you are doing. You would be manipulating the structure in its original form and your programmer peers would thank you for that. In terms of efficiency as you can see from the link below, the list is traversed until you find a match, any further appearances of the key are ignored.
The use of lists:keyfind() is another option less idiomatic probably so in my opinion looses points in favor of keeping consistency with the use of the structure as a proplist. The lists:keyfind() is a BIF which only tells us that is implemented in C not necessarily because of efficiency but very probable.
Finally the use of a list to dict in my opinion does not give you leverage on readability and you will be loosing consistency in terms of how the data structure was initially conceived, compared to the other two is probably the less efficient because you traverse the list to turn it to a dict and then you lookup the structure with the dict interface, so in my opinion you are loosing instead of gaining.
My two cents!
Upvotes: 1