Artalus
Artalus

Reputation: 1162

when(view) vs. switch(view.getId()) with Kotlin Android Extensions

I am fairly new to Android and Kotlin development and currently studying by tutorials, originally written for Java. In these there often occur patterns like:

void onSomething(View v) {
  switch(v.getId()) {
  case R.id.btn1:
    ...
  }    
}

However I am using Kotlin with Kotlin Android Extensions in my projects, which allows writing such switches as:

fun onSomething(v: View) {
  when (v) {
    btn1 -> { ... }
  }
}

The last one seems much more readable for me, but from what I understand, under the hood KAE transforms this handy UI identifiers' access into a sort of cache implemented with hash tables. Which might require kinda more heavylifting than comparing integers, depending on implementation. I am all for the readable code, but want to better understand the underlying magic of KAE.

So with that in mind,

1) is using View references in switches instead of IDs a good practice in Kotlin / KAE?

2) could it potentially impact my app's performance or memory footprint in a negative way, premature optimization aside?

Upvotes: 2

Views: 1907

Answers (1)

a_local_nobody
a_local_nobody

Reputation: 8191

is using View references in switches instead of IDs a good practice in Kotlin / KAE?

Well, the when statement is Kotlin's equivalent to Java's switch statement.

To provide some clarity for you, there's no reason why you can't do this:

fun onSomething(v: View) {
    when (v.id) {//do a switch on the id instead of the entire object
        R.id.something -> { ... }
    }
}

to answer your question regarding:

could it potentially impact my app's performance or memory footprint in a negative way, premature optimization aside?

I don't think either of these would really influence performance in such a way that you would notice it or in such a way that it would actually matter. If I had to guess, I'd say that the integer comparison of id's would be better than a comparison of the entire object.

Upvotes: 3

Related Questions