The costs of Kotlin Android Extensions

- 1 min


I am a big fan of the Kotlin Android Extensions as they helped me to get rid of copious amounts of boilerplate code.

Kotlin Android Extensions - Kotlin Programming Language

Thanks to it you can access to views directly referencing them by the Id.

However while I was implementing a ViewHolder I wanted to check how efficient is to use these extensions inside the bind method.

Here’s an example of a ViewHolder that uses a TextView using the Kotlin Android Extensions directly.

This apparently simple ViewHolder becomes very expensive without realization. We can decompile the Kotlin code to Java to see what is happening under the hood.

Go to Tools > Kotlin > Show Kotlin Bytecode and then click on Decompile

Accessing to itemView.title is actually performing itemView.findViewById( and this is exactly what you want to avoid in a ViewHolder.

Let’s move the call to itemView.title to the class construction:

Now let’s take a look at the new Java decompiled code:

As you can see, the findViewById is done on the constructor method and not on each bind call.

It wasn’t 100% for me on the documentation if findViewById was being called once, always or never. Compared to ButterKnife, where the View binding only happens once, the Kotlin Android Extensions can be a source of performance issues if used incorrectly.

Be careful (“ten cuidao”) on those parts of code where performance matters, don’t be afraid of decompiling the Bytecode to Java to understand it better.

Miquel Beltran

Miquel Beltran

Software engineer, Android specialist and newbie mentor

rss facebook twitter github youtube mail spotify instagram linkedin google google-plus pinterest medium vimeo stackoverflow reddit quora