Erlang 'catch' 表达式 vs try/catch 在效率方面

Erlang 'catch' expression vs try/catch in terms of efficiency

有人就此提出了类似的问题,但提出的问题并不完全相同。

我正在尝试安全地解码 base64 二进制文件,在输入可能不是二进制文件甚至不是 base64 编码的上下文中。

Erlang 说让它崩溃并处理它 -- 如果我这样做,最有效的方法是什么。在这个系统中,效率非常重要。

我知道要避免 try/catch,因为它会构建完整的堆栈跟踪——但是,catch 关键字对于此上下文是否合理? catch 关键字 faster/more 是否有效?

等函数中
safe_decode(Binary) ->
    case catch base64:decode(Binary) of
        <<Result/binary>> -> {ok, Result};
        {'EXIT', _} -> {not_base64, Binary}
    end.

这真的比 try catch 更有效吗?如何在效率很重要的系统中最好地处理这种情况,即涉及构建堆栈跟踪的崩溃 and/or 需要尽可能高效地处理比快乐路径更多的处理。

我只是在学习 erlang,所以也许答案就在眼前。

不,恰恰相反:避免使用 catch,因为它总是构建堆栈跟踪。 try+catch 仅在您使用 erlang:get_stacktrace().

要求时构建堆栈跟踪

查看 Heads-up: The cost of get_stacktrace(),由 Richard Carlsson 于 2013-11-05 发布到 erlang-questions,了解完整故事。我举几个部分:

(Executive summary: exceptions cheap, but erlang:get_stacktrace() kind of expensive; also, avoid 'catch Expr'.)

It's of course still valid to call get_stacktrace() in many situations, e.g. when the process is on its way to give up, or to write the crash information to a log, or for something that only happens rarely and the stack trace information is useful - but never in a library function that might be used heavily in a loop.

Finally, this is also another reason to rewrite old occurrences of 'catch Expr' into 'try Expr catch ... end' [...]