scala - Use of lazy val for caching string representation -
i encountered following code in jaxmag's scala special issue:
package com.weiglewilczek.gameoflife case class cell(x: int, y: int) { override def tostring = position private lazy val position = "(%s, %s)".format(x, y) }
does use of lazy val
in above code provide considerably more performance following code?
package com.weiglewilczek.gameoflife case class cell(x: int, y: int) { override def tostring = "(%s, %s)".format(x, y) }
or case of unnecessary optimization?
one thing note lazy vals that, while calculated once, every access them protected double-checked locking wrapper. necessary prevent 2 different threads attempting initialize value @ same time hilarious results. double-checked locking pretty efficient (now works in jvm), , won't require lock acquisition in cases, there more overhead simple value access.
additionally (and obviously), caching string representation of object, explicitly trading off cpu cycles possibly large increases in memory usage. strings in "def" version can garbage-collected, while in "lazy val" version not be.
finally, case performance questions, theory-based hypotheses mean nothing without fact-based benchmarking. you'll never know sure without profiling, might try , see.
Comments
Post a Comment