Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Kotlin inline functions and Android methods count

I want to understand how inline functions impact classes.dex and count of methods at all. From my understanding inline function should have zero overhead over methods count. However APK analyzer gives me opposite result. I wrote small test to check this.

InlineFunction.kt file:

inline fun inlined(block: () -> Unit) {
    block()
}

And MainActivity.kt file:

class MainActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        inlined {
            println("Inlined")
        }
    }
}

From perspective of generated code it looks pretty clear:

public final class MainActivity extends AppCompatActivity {
    private HashMap _$_findViewCache;

    protected void onCreate(@Nullable Bundle savedInstanceState) {
       super.onCreate(savedInstanceState);
       String var2 = "Inlined";
       System.out.println(var2);
   }

As we can see there is no call of additional method. But if I open apk with analyzer I can see that this method impacts defined and references methpds count.

enter image description here

On the other hand Kotlin stdlib impacts only referenced methods count and does not defined ones.

enter image description here

So what am I missing? I can't find how any good source about inlining methods in Android and how it is impact performance as well as I can't find any documentation how dex methods count is calculated.

I found Jake Wharton utility but if it works correct than all methods from Kotlin library impacts methods count. And it also means that something wrong in this answer https://stackoverflow.com/a/39635849/4727432

...Standard library is very small and many of its functions are inline-only which mean they don't exist past compilation and just become inline code. Proguard can take care of a lot as well...

So how does inline functions impact methods count? Any articles or posts which explain dex method counting process are welcome.

like image 666
hluhovskyi Avatar asked Jan 01 '18 16:01

hluhovskyi


Video Answer


1 Answers

Kotlin generates real methods even when they are marked inline for calling from java, so they are still reflected in the dex count.

Where inlining helps is overhead-free lambdas. Normally every lambda is represented with at least a method (sometimes even a class) in each place of invocation. But inlined lambdas skip this overhead, thus not affecting the dex count.

Standard library is very small and many of its functions are inline-only

The standard library uses a special trick (@inlineOnly annotation) for some methods to skip generating a method for an inline function (as I described above). But this annotation is internal in the kotlin package and cannot be used in normal code.

like image 54
voddan Avatar answered Nov 02 '22 07:11

voddan