Erlang : Which is more efficient in this scenario - using try catch or case statements?
erlang, performance
Solution
The case method will be more efficient, as it simply pattern matches, and does not involve building a call stack and stuff.
In both examples you are about to handle the "error" locally, so there is no point in the try catch.What you might see sometimes is something like:
fn2() ->
{ok, Result} = fn1(),
%Do stuff with Result
ok.
Here the intention is that you make fn2() throw a badmatch, if fn1() did not return ok. You let someone else "above" handle the problem. E.g. this might kill your process, and make your supervisor create a new one.
Problem
Say I have some function fn1() in Erlang which returns `{ok, Result}` if the function was executed successfully and `{error, "ErrorReason"}` if there was an error. Now in another function fn2() I call fn1() and I need to check the result of fn1 and proceed only if it is `{ok, Result}`. I figured, I can do this using either case or try catch. But Efficiency is my main concern and I'd like to know which of the two methods below is more efficient: `try-catch` Method ``` fn2() -> try {ok, Result} = fn1(), %Do something with Result ok catch throw:Term -> Term; exit:Reason -> {exit, Reason}; error:Reason -> {error,{Reason,erlang:get_stacktrace()}} end. ``` `case` Method ``` fn2() -> Res = fn1(), case Res of {ok, Result} -> %Do something with Result ok; {error, Reason} -> Reason end. ```