Cost of using lazy vals in Scala 2.13 and Scala 3

I have read that lazy vals are expensive and should not be used for optimisation but only for correctness. But most of these resources are from 2010-2016. Is that still the case with Scala 2.13 and Scala 3?

1 Like

Scala 3 allows you to mark lazy vals as @static (meaning they’ll be accessed from a single thread only) to speed them up further, and the algorithm used with non-static lazy vals has been microbenchmarked to be substantially faster than the Scala 2 one.

Regardless, the main use of lazy vals is for performance–to avoid computing expensive things until they are needed, hoping that either (1) they won’t actually be needed every time, or (2) the delay is more tolerable later than at creation-time (e.g. because it’s more spread out).

Sometimes you also need to use lazy vals for correctness, and if you need them for correctness you should definitely use them.

If you’re using them, when should you? As a general rule of thumb, if I’m going to do some simple math (maybe a couple trig functions at most) or create a small object, I just do it eagerly. If I’m going to do more, like duplicate a 100-element array, then I use lazy val instead if there’s a decent chance I might be able to skip the work altogether.

4 Likes

According to the current DottyDocs, that’s now called @threadUnsafe. (Wordier but clearer.) But otherwise, yeah.

3 Likes