`
轮回记忆
  • 浏览: 9964 次
  • 性别: Icon_minigender_1
  • 来自: 广州
最近访客 更多访客>>
社区版块
存档分类
最新评论

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

 
阅读更多
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不但代码美观,而且性能还相对出众.
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics