Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.

a

This page is for Scala performance coding hints that should be used for performance critical code, such as the repetitive places in the Daffodil runtime module.

...

See Cursor.scala for the traits.

Avoid Seq-like functions for Strings and Arrays

When writing in Scala, it usually feels natrual to treat Arrays as a sequence and Strings as a sequence of characters. For example

Code Block
scala
scala
val str = "Some String"
val hasSpaces = str.exists { _ == ' ' }

While this is convenient and feel's like "correct" Scala, in such cases Scala will implicity box the string with a StringOps to provide that extra functionality, requiring an allocation. Similarly, using Seq-like functions on an Array will also box he underlying array with an ArrayOps, again requiring allocation. Note that even simple things like the String apply()  function, e.g. str(4) , will cause such boxing. Instead, you should use the equivalent str.charAt(4). This is also a key difference between calling .size  on an array vs .length. The size method requires allocating an ArrayOps, while length will diretly acess the length from the java array primitive.

Note that in most cases, these allocations are so efficient that it likely won't affect performane. However, it's possible it could have an affect in a tight inner loop. At the very least, it avoids noise when profiling.