[erlang-questions] Efficiency of a list construction

Ladislav Lenart lenartlad@REDACTED
Fri May 20 13:30:16 CEST 2011


Hello.

I would like to point out that the two implementations are not
exactly the same because the tail recursive version returns
messages in the reverse order as opposed to the original
(non-tail recursive version), which does preserve the order
of received messages. The equivalent tail-recursive implementation
would be:

%% @spec() ->  [term()]
flush() ->
flush([]).

%% @hidden
flush(Msgs) ->
     receive
         Msg ->
             flush([Msg | Msgs]);
     after 17 ->
         lists:reverse(Msgs)    % added call to lists:reverse/1
     end.


However if the order is important I would use the original
non-tail recursive version. For example lists:map/2 uses
non-tail recursive approach as well.


Ladislav Lenart


On 20.5.2011 13:08, Paul Barry wrote:
> Interesting response.
>
> I'm currently working my way through both Joe's book and
> Francesco/Simon's.  As this is Erlang, I'm reading the two books in
> parallel (of course).
>
> Both books talk about the efficiency of tail recursion over direct
> recursion with a bit of talk about how the run-time may optimize for
> code that isn't tail recursive to improve its performance.  The
> suggestion seems to be that in older versions of the run-time, tail
> recursion won hands down, but that nowadays this may not always be the
> case.  Is there an update on this?
>
> Of course, Joe's book suggests that the only way to *really* know is
> to measure (good advice).  Using "timer:tc" (as described on page 107
> of the Francesco/Simon book) might be a good place to start.
>
> Regards.
>
> Paul.
>
>
> On 20 May 2011 11:50, Vance Shipley<vances@REDACTED>  wrote:
>> Kannan,
>>
>> No, it is not tail recursive.  This is:
>>
>>      %% @spec() ->  [term()]
>>      %%
>>      flush() ->
>>         flush([]).
>>
>>      %% @hidden
>>      flush(Msgs) ->
>>         receive
>>                 Msg ->
>>                         flush([Msg | Msgs]);
>>         after 17 ->
>>                 Msgs
>>         end.
>>
>> On Fri, May 20, 2011 at 03:45:19PM +0530, Kannan wrote:
>> }  Is the following list construction an efficient one?
>> }
>> }  flush() ->
>> }      receive
>> }  Msg ->
>> }      [Msg|flush()]
>> }      after 17 ->
>> }      []
>> }      end.
>>
>> --
>>         -Vance
>> _______________________________________________
>> erlang-questions mailing list
>> erlang-questions@REDACTED
>> http://erlang.org/mailman/listinfo/erlang-questions
>>
>
>
>





More information about the erlang-questions mailing list