[erlang-questions] Efficiency of function call

fishball fishballian@REDACTED
Tue Jun 17 08:43:53 CEST 2014


Hi
As I read the Efficiency Guide, I found something interesting:(see http://www.erlang.org/doc/efficiency_guide/functions.html#id67357)
Here is an intentionally rough guide to the relative costs of different kinds of calls. It is based on benchmark figures run on Solaris/Sparc:
Calls to local or external functions (foo(), m:foo()) are the fastest kind of calls.

Calling or applying a fun (Fun(), apply(Fun, [])) is about three times as expensive as calling a local function.

Applying an exported function (Mod:Name(), apply(Mod, Name, [])) is about twice as expensive as calling a fun, or about six times as expensive as calling a local function.


But I get another result when I run these code in my computer:
foo() ->
    ok.
test() ->
    List = lists:seq(1, 50000000),
    statistics(wall_clock),
    statistics(runtime),
    %% [foo() || _ <- List],                               %%test result 358 ~ 358
    %% [?MODULE:foo() || _ <- List],                %%test result 358 ~ 358
    %% [apply(?MODULE, foo, [] || _ <- List],     %%test result 358 ~ 358
    [apply(fun() -> ok end, []) || _ <- List],         %%test result 2247 ~ 1716
    {_, Time1} = statistics(wall_clock),
    {_, Time2} = statistics(runtime),
    io:format("calc ~p ~~ ~p~n", [Time1, Time2]).Applying a fun is even slower than apply/3, Why?
I also notice "apply/3 must look up the code for the function to execute in a hash table. Therefore, it will always be slower than a direct call or a fun call".
So I test in my project which include many modules and I get the same result.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://erlang.org/pipermail/erlang-questions/attachments/20140617/c7330356/attachment.htm>


More information about the erlang-questions mailing list