是否在Erlang中优化了别名函数

nia*_*hoo 3 compiler-construction erlang optimization

假设我有一个从模块导出的功能,但模块多次使用该功能.

所以我写了一个别名,因为我在编码时很懒.

-export([get_toolkit/0]).

get_toolkit() -> 
    ... code ... code ... 
    ... code ... code ... 
    ... code ... code ... 
    {ok, Thing}.

tk() -> get_toolkit().
Run Code Online (Sandbox Code Playgroud)

编译器是否优化了别名?

谢谢

Jr0*_*Jr0 5

我认为这将花费你一个间接费用.我这样说是因为我接受了这段代码

-module(testit).
-export([get_toolkit/0, long/0, short/0]).

get_toolkit() -> 
    _ = lists:seq(1,100),
    {ok, thing}.

tk() -> 
   get_toolkit().

long() ->
    get_toolkit(),
    {ok, thing2}.

short() ->
    tk(),
    {ok, thing3}.
Run Code Online (Sandbox Code Playgroud)

并通过erlc -S testit.erl生成了ASM,它给了我

SNIP

{function, tk, 0, 4}.
  {label,3}.
    {line,[{location,"testit.erl",8}]}.
    {func_info,{atom,testit},{atom,tk},0}.
  {label,4}.
    {call_only,0,{f,2}}.


{function, long, 0, 6}.
  {label,5}.
    {line,[{location,"testit.erl",11}]}.
    {func_info,{atom,testit},{atom,long},0}.
  {label,6}.
    {allocate,0,0}.
    {line,[{location,"testit.erl",12}]}.
    {call,0,{f,2}}.
    {move,{literal,{ok,thing2}},{x,0}}.
    {deallocate,0}.
    return.


{function, short, 0, 8}.
  {label,7}.
    {line,[{location,"testit.erl",15}]}.
    {func_info,{atom,testit},{atom,short},0}.
  {label,8}.
    {allocate,0,0}.
    {line,[{location,"testit.erl",16}]}.
    {call,0,{f,4}}.
    {move,{literal,{ok,thing3}},{x,0}}.
    {deallocate,0}.
    return.
Run Code Online (Sandbox Code Playgroud)
  • 剪辑中列出的第一个函数是"短手"函数,tk/0.
  • 第二个是调用get_toolkit/0的long函数,
  • 第三个是使用tk/0短手的短函数

ASM显示最后一个函数(使用tk/0的函数)调用tk/0({call,0,{f,4}}),后者又调用get_toolkit/0({call,0,{f,2 }}).使用get_toolkit/0的函数直接调用get_toolkit/0({call,0,{f,2}}).

所以,我认为没有应用优化.

另外,我做了一些似乎支持这个假设的时间测试;)