[erlang-questions] list comprehensions speed

Richard A. O'Keefe ok@REDACTED
Tue Feb 25 22:06:43 CET 2014


On 26/02/2014, at 2:08 AM, Oleg wrote:
[which is faster?]

You have the code.  Why not benchmark it yourself?

>  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")].

Let's start by observing the
string:equal(S, S) -> true;
string:equal(_, _) -> false.

so this is just

	[Value || {"name3",Value} <- A]

> 
> 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.

And this is just

get_value(Key, [{Key,Value}|_]) -> [Value];
get_value(Key, [{_,  _    }|T]) -> get_value(Key, T);
get_value(_,   []             ) -> [].

Now I can see that the two approaches do different things.
The list comprehension always searches the whole list.
get_value/2, however, stops as soon as it finds a match.

As a specific example,
  List = [{"foo",1},{"foo",2}],
  [Value || {"foo",Value} <- List]
answers
  [1,2]
but
  get_value("foo", List)
answers
  [1].




More information about the erlang-questions mailing list