This means that each captured variable will be passed as constructor arguments, thus generating a memory overhead. Also, index 56 shows how Kotlin captures the random variable. Then we can spot from index 51 that the JVM creates a new instance of MainKt$main$1 inner class for each invocation. How are we so sure about this? Let’s reinvent another wheel by declaring a function to apply a function on each collection element: fun Collection.each(block: (T) -> Unit) // capturing the random variableĪnd if we take a peek inside the bytecode using javap: > javap -c MainKtĥ6: invokespecial #33 // Method MainKt$main$1."":(F)Vĥ9: checkcast #35 // class kotlin/jvm/functions/Function1Ħ2: invokestatic #41 // Method CollectionsKt.each:(Ljava/util/Collection Lkotlin/jvm/functions/Function1 )V For non-capturing lambdas, there will be only one instance, a singleton, of those function types. The extra memory allocations get even worse when a lambda captures a variable: The JVM creates a function type instance on every invocation. Just like with the latter, a lambda expression can access its closure, that is, variables declared in the outer scope. When a lambda captures a variable from its closure, Kotlin stores the variable along with the capturing lambda code.
0 Comments
Leave a Reply. |
AuthorWrite something about yourself. No need to be fancy, just an overview. ArchivesCategories |