Is `{ person: Person -> person.age }` really th...
# getting-started
s
Is
{ person: Person -> person.age }
really the same thing as
Person::age
in terms of performance and memory? Is the usage of the method reference also creating a new lambda that needs to be garbage collected after the method/function it was used in is done? If so, this would surprise me. My feeling was that
Person::age
should point to something that already exists instead of creating something new. And if used, it should be cached so that calling it 100x would not create 100 lambdas that need to be collected. 🤔 The only thing I found for was for Java and it said that method references are very slightly faster because they don’t need to capture the context. ( I did not test this myself so far with a profiler. )
1
y
My understanding is that lambdas with no captures are cached by the Kotlin compiler
s
When you explicitly declare an object, a new instance is cre- ated on each invocation. With a lambda, the situation is different: if the lambda doesn’t access any variables from the function where it’s defined, the corresponding anonymous class instance is reused between calls
Right. That would be the quote from Kotlin in Action v2 what I’m currently reading. So since method references capture no context they are lambdas that are never GCed?
Is a „bound callable reference“ also cached or will a new one created for every new object (since the object it refers to is considered context)? 🤔
y
I believe a bound one would be recreated, yes, because it has to re-reference the object every time. Not sure actually what GCing would look like for the lambdas that capture nothing. My best guess would be is that they work similarly to
object
declarations.
👍 1
thank you color 1