


We are testing three variants to parse a number, and fallback to 0 if parsing fails (it does fail in the test): To run the tests, I’ve used the sbt-jmh plugin, running on my 2018 i9 MBP, using both Java 11 and Java 17 from Azul Zulu. No exceptions are involved and the whole process is a lot faster. toIntOption method which is a completely different implementation than.

What’s the alternative? Turns out Scala 2.13 introduced a new. As the name suggests, exceptions should be used for exceptional cases, not in the regular case. The problem is that every time parsing fails, an exception is being thrown, and this implies creating the stack trace, which is a slow operation. To the degree that this might be the decisive factor when it comes to the latency of your application. What can go wrong? Well, if the number-parsing is on your code’s hot path - that is, called frequently - and if the value is often not a number (that is, parsing fails), you’ll see really poor performance. Hence, typical number-parsing presents itself as follows: Try(value.toInt).toOption That’s why we usually catch the exception that might occur during parsing and convert the result to an Either or Option. toInt method simply calls Java’s Integer.parseInt, which does exactly the same.īeing Scala programmers, we don’t use exceptions often, if at all. However, what happens if the value is not an integer? Well, a exception will be thrown. With Scala, that’s easy - given a value: String, just call value.toInt. Every now and then, we’ve got to parse a String into an Int or Double.
