exception timing
Today a quick experiment to examine different ways to handle errors in Scala. I’ll be doing this all in the scala
REPL.
First, lets define a timer method that takes a function as an argument and runs it 1,000 times, then prints the elapsed time in ms:
Next we’ll define a “safe” function that returns an Int
, a function that returns a case class
, and finally a function that throws an Exception
:
Now let’s run them thru the timer:
The results are not too surprising. We can see that when an “error” case is needed in a decision tree, it is much more cost effective to return a custom “Error wrapper” case class with details than it is to throw an exception. In fact it performs twice as fast. It pays to think about error handling and performance.