[erlang-questions] continuation vs. accumulator

June Kim juneaftn@REDACTED
Mon Jul 30 11:49:59 CEST 2007


2007/7/30, Matthew Dempsky <matthew@REDACTED>:
> On 7/29/07, June Kim <juneaftn@REDACTED> wrote:
> > Why is continuation passing style faster than accumulator passing
> > style in erlang?
>
> It's not.  Your CPS implementation evaluates (...(((1 * 2) * 3) * 4) *
> ...) while your APS implementation evaluates 1 * (2 * (3 * (4 *
> ...))).  Your APS implementation handles larger integers during its
> execution, which accounts for the slow down.
>
> On my laptop, the following code outperforms all three of your implementations.
>
> fact_aps2(N) -> fact_aps2(N,1,1).
> fact_aps2(N,M,Acc) ->
>    Acc2 = M * Acc,
>    if N == M -> Acc2;
>       true -> fact_aps2(N,M + 1,Acc2)
>    end.

Yeah, when N is small, but again, there isn't a big difference. When N=30000:

fact:         2516000 us
fact_aps:  2875000 us
fact_aps2:2562000 us
fact_cps:  2672000 us

As you see fact is stil the fastest. (but when there isn't enough
memory the page swap might happen and fact gets the last rank)

On the other hand, when N is, for instance, 80000, fact_aps takes 28
secs whereas fact_aps2 takes about 49 secs and fact_cps takes about 50
secs.



More information about the erlang-questions mailing list