Hey all, was playing around with byte code when I saw that there’s quite some difference between function referencing and using lambda to call same function. Assume listen
is following function:
fun listen(text: String) {
Log.i("Listener", text)
}
When I pass it as reference as in
SomeSingleton.listener = ::listen
following byte code is generated:
SomeSingleton.INSTANCE.setListener((Function1)(new Function1((MainActivity)this) {
// $FF: synthetic method
// $FF: bridge method
public Object invoke(Object var1) {
this.invoke((String)var1);
return Unit.INSTANCE;
}
public final void invoke(@NotNull String p1) {
Intrinsics.checkParameterIsNotNull(p1, "p1");
((MainActivity)this.receiver).listen(p1);
}
public final KDeclarationContainer getOwner() {
return Reflection.getOrCreateKotlinClass(MainActivity.class);
}
public final String getName() {
return "listen";
}
public final String getSignature() {
return "listen(Ljava/lang/String;)V";
}
}));
But if I use it as in
SomeSingleton.listener = {
listen(it)
}
this is generated instead:
SomeSingleton.INSTANCE.setListener((Function1)(new Function1() {
// $FF: synthetic method
// $FF: bridge method
public Object invoke(Object var1) {
this.invoke((String)var1);
return Unit.INSTANCE;
}
public final void invoke(@NotNull String it) {
Intrinsics.checkParameterIsNotNull(it, "it");
MainActivity.this.listen(it);
}
}));
Thus is it, in general practice, more efficient to wrap methods with lambdas instead of method referencing ?