多函数匹配与单函数判断的性能比较(转载)

Erlang中应用了大量的匹配语法,那么到底是多函数的when匹配性能好还是单个函数里的case of性能更加出众,马上做个比较:

程序echo1:
C代码 收藏代码

-module(echo1).
-export([start/1]).

start(N) ->
statistics(runtime),
run(N,1),
{_, T} = statistics(runtime),
io:format("total running time: ~p ms ~n", [T]).

run(N,S) ->
case N==S of
true -> true;
_ ->
case S rem 2 of
true -> true;
_ ->ok
end,
run(N,S+1)
end.


程序echo2:
C代码 收藏代码

-module(echo2).
-export([start/1]).

start(N) ->
statistics(runtime),
run(N,1),
{_, T} = statistics(runtime),
io:format("total running time: ~p ms ~n", [T]).

run(N,N) -> true;
run(N,S) when S rem 2 == 0 -> true,run(N,S+1);
run(N,S) -> run(N,S+1).


运行结果:
> echo1:start(100000000).
total running time: 5891 ms
ok

> echo2:start(100000000).
total running time: 4344 ms
ok


很明显地看出方案2的性能比方案1高出30%左右,看来方案2不但代码美观,而且性能还相对出众.
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值