Language-Level LazyVals in Scala
[This is from http://www.nabble.com/Question-on-lazy-val-td17678892.html]
For what it’s worth, I fast-coded a hack that implements lazy vals at the language level, mimicking the compiler’s implementation. It turns out 120% slower that built-in lazy vals, if using the client HotSpot (default) and 40% slower if using the server HotSpot (java -server).
It does not leak (?) and the memory footprint is worse than the built-in solution.
final class LazyVal[A](f: => A) {
private[this] var _f = f _
private[this] var _value = null.asInstanceOf[A]
def value = {
if(null != _f) synchronized {
if(null != _f) {
_value = _f()
_f = null
}
}
_value
}
}
The private[this] things are needed so that field accesses (as compiled by scalac) do not go through methods, although I have noticed that HotSpot is doing a great job even without them.
Tags: scala