I have a DAO object which I defined as a case class.
case class StudentDAO(id: Int) {
def getGPA: Double = // Expensive database lookup goes here
def getRank: Int = // Another expensive database operation and computation goes here
def getScoreCard: File = // Expensive file lookup goes here
}
I would naturally make getGPA
and getRank
and getScoreCard
def
s and not val
s because I don't want them to be computed before they may be used.
What would be the performance impact if I marked these methods as lazy val
s instead of def
s? The reason I want to make them lazy val
s is: I do not want to recompute the rank each time for a Student with id "i".
I am hoping that this will not be marked as duplicate because there are several questions as below which are mostly about differences:
When to use val, def, and lazy val in Scala?
def or val or lazy val for grammar rules?
`def` vs `val` vs `lazy val` evaluation in Scala
This question is mainly aimed towards the expenses (tradeoffs between CPU vs. memory) in making a method
a lazy val
for costly operations and what would one suggest over other and why?
EDIT: Thank you for the comment @om-nom-nom. I should have been more clear with what I was looking for.
I read here:
Use of lazy val for caching string representation
that string representation of the object is cached (see @Dave Griffith's answer). More precisely I am looking at the impact of Garbage Collection if I made it a lazy val
instead of def