mayhilt.blogg.se

Scala convert string to long
Scala convert string to long












scala convert string to long

toIntOption approach is 500x faster than the other ones: ingTry thrpt 25 712466.231 ± 3966.962 ops/s The results are more than surprising! The. Here’s the code: class IntParsing usingTry: Int = usingCatch: Int =Ĭase _: Exception => usingOption: Int = "abc".toIntOption.getOrElse(0) using a traditional try-catch, in case it was the Try that is adding overhead, and not the exception-throwing.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.

scala convert string to long

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.














Scala convert string to long