Optimization of list comprehensions?

Robert Virding rv@REDACTED
Tue Feb 6 11:30:48 CET 2001

David Gould <dg@REDACTED> writes:
>I really like list comprehensions, they seem so, declarative. I am tempted
>to use them everywhere ;-)
>But, what does the compiler do with them?
>Does it generate better code for a list comprehension than for using

The current (R7) compiler does a reasonable job with and the code is 
comaprable to using lists:map.  The new R8 compiler will do a better 
job, but it very much depends on what you do in the lc/map which is the 
faster.  Lc's shouldn't be slower.

>Is it able to detect when a listcomp is used for its side effects alone and
>not build the result? For example, is:
> [io:format('~s~n', [Item]) | Item <- Items].
>more or less effcient than:
> lists:foreach(fun(Item) -> io:format('~s~n', [Item])) end, Items).
>Oh yeah, is it better or worse style?

The compiler does not detect if a comprehension is used for side effects
alone.  It is, however, definitely much worse style not to use
lists:foreach or lists:map where appropriate.  lists:foreach explicitly
says "do this for each element and throw away the result" while
comprehensions say "take elements from generators, filter out unwanted 
cases and build list of values like this".

You should always try and be clear.  Anyway we are looking at how to 
optimise calls to useful functions in the standard libraries, like 
lists:map and lists:foreach.


Robert Virding                          Tel: +46 (0)8 545 55 017
Alteon Web Systems                      Email: rv@REDACTED
S:t Eriksgatan 44                       WWW: http://www.bluetail.com/~rv
SE-112 34 Stockholm, SWEDEN
"Folk säger att jag inte bryr mig om någonting, men det skiter jag i".

More information about the erlang-questions mailing list