[erlang-questions] Erlang list comprehension optimization

Robert Virding <>
Wed Mar 17 05:07:09 CET 2010


On 17 March 2010 04:28, Bernard Duggan <> wrote:
> Vinayak Pawar wrote:
>> Are these equivalent in terms of space utilization?
>>
>> 1) lists:foreach(fun(X) -> SomeOpFun(X) end, Xs).
>>
>> 2) [SomeOpFun(X) || X <- Xs].
>>
>> In case 1) output list isn't generated. In case 2) output list is generated,
>> but it is not used(or not assigned to any variable). So in such cases, does
>> Erlang VM optimize and doesn't create any temporary list?
>>
> From
> http://www.erlang.org/doc/efficiency_guide/listHandling.html#id2261027 :
>
> "In R12B [and presumably later], if the result of the list comprehension
> will *obviously* not be used, a list will not be constructed."

That is obviously good when it can be done although there are cases
when the list must still be created even if it not wanted, for example
if the list comprehension is the last thing done in a function so its
value must be returned.

There is one strange thing further up in the text:

"Lists comprehensions still have a reputation for being slow. They
used to be implemented using funs, which used to be slow."

List comprehensions have never been implemented with funs, at least
not when they were first introduced. I know.

Robert


More information about the erlang-questions mailing list