[erlang-questions] Parameterized module idioms

Sebastien Merle s.merle@REDACTED
Thu Apr 22 11:48:59 CEST 2010


Taking about numbers, I was interested in the difference
between parametrized modules and closures call overhead.

And the result is that parametrized modules seems to be
nearly two times faster than closure:

  1> test:test(100000000).
  [{closure,10756202},{module,6001309}]

Here's the code:

----------------------------------------
-module(test).

-export([test/1,
         call/3]).

-record(?MODULE, {count = 0}).

test(Count) ->
    C = time(fun test_closure/1, Count),
    M = time(fun test_module/1, Count),
    [{closure, C}, {module, M}].

time(F, A) ->
    T1 = erlang:now(),
    F(A),
    T2 = erlang:now(),
    timer:now_diff(T2, T1).

test_closure(Count) ->
    C1 = new_closure(42),
    C2 = new_closure(18),
    C1(call, {C2, Count}).

test_module(Count) ->
    M1 = new_module(42),
    M2 = new_module(18),
    M1:call(M2, Count).

new_closure(Start) -> make_closure(#?MODULE{count = Start}).

new_module(Start) -> #?MODULE{count = Start}.

call_closure(_Other, 0, State) -> State#?MODULE.count;
call_closure(Other, Count, State) ->
    NewState = State#?MODULE{count = State#?MODULE.count + 1},
    Other(call, {make_closure(NewState), Count - 1}).

call_module(_Other, 0, State) -> State#?MODULE.count;
call_module(Other, Count, State) ->
    NewState = State#?MODULE{count = State#?MODULE.count + 1},
    Other:call(NewState, Count - 1).

call(Other, Count, State) -> call_module(Other, Count, State).

make_closure(State) ->
    fun(call, {Other, Count}) -> call_closure(Other, Count, State) end.
----------------------------------------

And yes I know it's not a real parametrized module,
but the function calls are equivalent, isn't it ?


-- 
Sebastien Merle.


More information about the erlang-questions mailing list