Optimization of list comprehensions?

Richard Carlsson <>
Tue Feb 6 09:55:35 CET 2001


On Mon, 5 Feb 2001, David Gould wrote:

> 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
> lists:map()?

Up until now, list comprehensions have not been efficiently compiled, but
as of the coming R8 release they will be as efficient as the hand-coded
versions, i.e.:

	do(Xs) -> [foo(X) || X <- Xs].

will be as quick as:

	do([X | Xs]) -> [foo(X) | do(Xs)];
	do([]) -> [].

And in fact, there is some potential for generating even better code for
list comprehensions than for explicitly recursive functions.

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

It could be done, but don't expect it to happen any time soon. (Actually,
that sort of optimisation - a form of specialisation - applies to other
code as well, not only list comprehensions.)

> Oh yeah, is it better or worse style?

I'd say the "foreach" version is better style in this case, since it is
less obvious to the eye (even if it is actually the case) that the calls
will be executed in the expected order in the list comprehension version.

	/Richard Carlsson


Richard Carlsson ()   (This space intentionally left blank.)
E-mail: 	WWW: http://www.csd.uu.se/~richardc/




More information about the erlang-questions mailing list