Issue
I have some code that generates large amounts of instances of a small data class. When I added one lazy property to the class I noticed that creating instances of this class became much slower even if the lazy property is never accessed. How come this happens? I was expecting that there would be no difference if the lazy property is never accessed. Is there any way of using lazy properties without taking this kind of performance hit?
Here's a minimal example:
import kotlin.system.measureTimeMillis
class LazyTest(val x: Int) {
val test: Int by lazy { 9 }
}
fun main(){
val time = measureTimeMillis { List(500_000) {LazyTest(it) }}
println("time: $time")
}
When running this on on play.kotlinlang.org it takes 500-600 milliseconds, if I comment out the line val test: Int by lazy { 9 } it instead takes around 40 milliseconds to run.
Solution
Using by lazy creates a second object to "hold the laziness," implementing the lazy calculation. This is most likely responsible for the slowdown.
Answered By - Louis Wasserman
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.