[erlang-questions] At what point am I "playing compiler"

Per Melin per.melin@REDACTED
Sun May 17 22:40:18 CEST 2009


Dennis Byrne:
> The functions expressive/0 and efficient/0 have the same result.
> Sometimes I prefer expressive syntax but I am concerned about
> efficiency.  Should Erlang developers worry about this or do any of
> the compilers (or runtime) make these concerns obselete?
>
> expressive() ->
>        List = [1,2,3],
>        Last = lists:last(List),
>        Min = lists:foldl(fun min/2, Last, List),
>        Max = lists:foldl(fun max/2, Last, List),
>        Sum = lists:foldl(fun sum/2, 0, List),
>        {Min, Max, Sum}.
>
> efficient() ->
>        List = [1,2,3],
>        Last = lists:last(List),
>        lists:foldl(fun summary/2, {Last, Last, 0}, List).
>
> summary(X, {Min, Max, Total}) ->
>        {min(X, Min), max(X, Max), Total + X}.
>
> sum(X, Y) ->
>        X + Y.
>
> min(X, Y) when X < Y ->
>        X;
> min(_, Y) ->
>        Y.
>
> max(X, Y) when X > Y ->
>        X;
> max(_, Y) ->
>        Y.

How about:

expressive_and_efficient() ->
    List = [1,2,3],
    {lists:min(List), lists:max(List), lists:sum(List)}.

:-)

I run micro-benchmarks obsessively. On my machine expressive() is 70%
slower than efficient() without HIPE and 150% slower with HIPE. But
we're talking fractions of a microsecond per execution. Should you
bother?

If you're concerned with efficiency, timer:tc/3 is your friend. Stuff
like this you should obviously loop at least a few million times to
get reliable times.



More information about the erlang-questions mailing list