A bit of context:
case class Finger(length: Int)
case class Arm(thumb: Finger)
case class Body(rightArm: Arm, leftArm: Arm)
case class Human(body: Body)
def processHumanFinger(human: Human) = println(human.body.rightArm.thumb.length)
def processFingerOnly(finger: Finger) = println(finger.length)
val john = Human(Body(Arm(Finger(1)), Arm(Finger(3))))
val johnFinger = john.body.rightArm.thumb.length
I was wondering what was the difference in memory and time costs between those two pieces of code :
(1 to 1000000).foreach(_ => processFingerOnly(johnFinger))
and
(1 to 1000000).foreach(_ => processHumanFinger(john))
My question is mainly about knowing if the cost of accessing the human object in depth a million times (sample 2) is more expensive (in time and/or memory) than accessing it in depth once when assigning the val johnFinger
then passing only the Finger
object to the function (sample 1). But I am interested in every differences that exists between these two pieces of code !
Using the following code, you can do a check to see how long each sample took.
Preparation
case class Finger(length: Int)
case class Arm(thumb: Finger)
case class Body(rightArm: Arm, leftArm: Arm)
case class Human(body: Body)
def processHumanFinger(human: Human) = human.body.rightArm.thumb.length
def processFingerOnly(finger: Finger) = finger.length
val john = Human(Body(Arm(Finger(1)), Arm(Finger(3))))
val johnFinger = john.body.rightArm.thumb.length
def time[R](block: => R): R = {
val t0 = System.nanoTime()
val result = block // call-by-name
val t1 = System.nanoTime()
println("Elapsed time: " + (t1 - t0) + "ns")
result
}
time {(1 to 10000000).foreach(_ => processFingerOnly(johnFinger))}
time {(1 to 10000000).foreach(_ => processHumanFinger(john))}
Through this simple timer, we can see that accessing an object at 1-level is around twice as fast as accessing an object at 4-level.
However, this could be a naiive approach, so I'm more than happy to hear people's opinions and feel free to edit!
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.