[erlang-questions] list comprehensions speed
Garrett Smith
g@REDACTED
Tue Feb 25 16:12:17 CET 2014
On Tue, Feb 25, 2014 at 2:08 PM, Oleg <lego12239@REDACTED> wrote:
> Hello.
>
> I'm erlang newbie. Don't beat me, please :-)
This is list is typically very docile -- but, for example, if you
propose that Ericsson rename list comprehensions to "enumeration
generators" to to appeal to Java programmers, well, brace yourself.
> 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")].
>
> 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).
I have questions like this all the time. I use this thing to answer my
own questions:
https://github.com/gar1t/erlang-bench
As I've stated emphatically before, these stats, like all stats, lie.
*But* they are at least some attempt to measure and test.
This particular test I think is similar to what you're looking for:
https://github.com/gar1t/erlang-bench/blob/master/name-lookup.escript
As Sean Cribbs pointed out, lists:keyfind/2 has super powers. I don't
know at under what conditions it makes sense to move from its blazing
fast O(N) scans to log(N) hash/tree lookups. Of course this can be
tested.
As Loïc Hoguin has pointed out, with zeal, performance characteristics
tend to change under system load. I haven't seen what he's seen
specifically, but he's very emphatic.
And as Richard O'Keefe has pointed out, focus on getting your program
to work correctly before worrying about performance.
And as Joe Armstrong has pointed out, performance considerations comes
after correctness *and* maintainability, except for known performance
bottlenecks where it pays to make a compromise.
I'd say, get in the habit of answering your own questions when it
comes to "speed" -- I suggest playing around with erlang-bench, as
it's super fun :)
If you come up something interesting as an erlang-bench script, please
pass it along as a pull request.
Best of luck with your Erlang adventures!
Garrett
More information about the erlang-questions
mailing list