[erlang-questions] list comprehensions speed

Loïc Hoguin <>
Tue Feb 25 15:43:18 CET 2014


On 02/25/2014 02:08 PM, Oleg wrote:
>    Hello.
>
> I'm erlang newbie. Don't beat me, please :-), if this question is obvious.
>
> I have a list of key-value pairs:
>
> A=[{"name1", 1}, {"name2", 77}, {"name3", 33}, {"name4", 234}].
>
> What is faster:
>
> [ Value || {Name, Value} <- A, string:equal(Name, "name3")].

This walks through the whole list regardless of "name3" being found yet, 
and might return more than one value.

> Or:
>
> get_value(Key, []) ->
>    [].
> get_value(Key, [H|T]) ->
>    {Name, Value} = H,
>    case string:equal(Name, Key) of
>      true ->
>        [Value];
>      false ->
>        get_value(Key, T)
>    end.
>
> start() ->
>    get_value("name3", A).

This returns immediately when "name3" is found. It also only returns the 
first "name3" it finds. This is potentially million times faster 
depending on the size of the list. As others have pointed out, this is 
more or less lists:keyfind/3, that I advise you to use.

-- 
Loïc Hoguin
http://ninenines.eu



More information about the erlang-questions mailing list