erlang catch时间分析

本文通过测试对比了Erlang中在处理大量数据时,使用catch捕获throw抛出的异常与正常运行的效率差异。测试结果显示,当所有数据都正常运行时,catch的效率高于直接返回,但当所有数据都throw抛出时,catch效率较低。此外,catch虽然使代码更直观,但在大量throw的情况下会增加开销。

下面的测试,构造了一个1000W长度的列表,用于进行循环测试
主函数体为:

test(Lv, Star) ->
    CheckList = [{lv, Lv}, {star, Star}],
    List = lists:seq(1, 10000000),
    StarTime = erlang:system_time(milli_seconds),
    [case check_list(CheckList) of
         true -> true;
         {error, _Error} -> skip
     end || _X <- List],
    EndTime = erlang:system_time(milli_seconds),
    io:format("1 need_time : ~p~n", [EndTime - StarTime]),
    StarTime1 = erlang:system_time(milli_seconds),
    [case catch other_check(CheckList) of
            true -> true;
            {error, _False} -> skip
    end || _X <- List],
    EndTime1 = erlang:system_time(milli_seconds),
    io:format("2 need_time : ~p~n", [EndTime1 - StarTime1]).

1、第一种情况
当所有数据都是throw抛出时,catch效率要明显比直接返回的效率要低
当所有数据都是正常运行时,catch效率要比下面使用列表的高,原因是下面列表需要递归判断

other_check([{lv, Lv}, {star, Star}]) ->
    if
        Lv > 10 -> true;
        true -> throw({error, false})
    end,
    if
        Star > 30 -> true;
        true -> throw({error, false})
    end.

check_list([]) -> true;
check_list([{Type, Num} | T]) ->
    case check(Type, Num) of
        true -> check_list(T);
        {error, Error} -> {error, Error}
    end.

check(lv, Lv) ->
    if
        Lv > 10 -> true;
        true -> {error, 2}
    end;

check(star, Star) ->
    if
        Star > 30 -> true;
        true -> {error, 3}
    end.


运行结果:
1> c(test).
{ok,test}
2> test:test(10,30).
1 need_time : 235
2 need_time : 1484
ok
3> test:test(11,31).
1 need_time : 516
2 need_time : 312

2、第二种情况
当所有数据都是throw抛出时,catch效率要明显比直接返回的效率要低
当所有数据都是正常运行时,catch效率也要比下面嵌套判断的低
缺点:需要嵌套判断,容易让代码变得臃肿

other_check([{lv, Lv}, {star, Star}]) ->
    if
        Lv > 10 -> true;
        true -> throw({error, false})
    end,
    if
        Star > 30 -> true;
        true -> throw({error, false})
    end.

check_list([{lv, Lv}, {star, Star}]) ->
    if
        Lv > 10 ->
            if
                Star > 30 -> true;
                true -> {error, 3}
            end;
        true -> {error, 2}
    end.

运行结果:
1> c(test2).
{ok,test2}
2> test2:test(10,30).
1 need_time : 219
2 need_time : 1484
ok
3> test2:test(11,31).
1 need_time : 296
2 need_time : 329
ok

总结:上述都是对于时间的测量,并没有涉及到其他如性能上面的开销,对于少量用户数据正确来说,catch的使用能让代码更加直观、简洁;但如果大量的throw会加大一些开销。

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值