3

The question has been asked in many forms and for many times here and here; But I want to confirm one thing and my questions is very simple: Does android:onClick use Java reflection?

Since Java reflection slows down the performance as explained here, I would never like to code in inefficient manner.

I just want a simple answer: yes (only if you are sure about that) or no?

EDIT:

There are many answers on SO conflicting the understanding:

For example, See this one and this one. Both have accepted answers and both are saying two different things. (thats only why I posted the question.)

Community
  • 1
  • 1
xyz
  • 1,325
  • 5
  • 26
  • 50
  • 2
    Why don't you *try* to use `onClick` and see if it is efficient enough for your use case instead of speculating in how it works internally and upon that do some premature opmitization. – aioobe Sep 16 '14 at 21:17
  • @aioobe how to check about that kind of optimization? I don't know. – xyz Sep 16 '14 at 21:18
  • @CaptainGiraffe No. since it has been already mentioned in the question. – xyz Sep 16 '14 at 21:21
  • @CaptainGiraffe where it is written in the answer that "android:onclick uses/does not use java reflection"? – xyz Sep 16 '14 at 21:23

2 Answers2

2

Indeed it does use reflection to bind the method("methodName") to the handler. This is a one time deal while inflating the XML and does not affect performance in any meaningful way. The XML inflation is in itself is a rather costly parse,

(Per http://grepcode.com/file/repository.grepcode.com/java/ext/com.google.android/android/2.1_r2/android/view/View.java#2017)

Besides this, it is exactly like the doing it in code.

Captain Giraffe
  • 14,407
  • 6
  • 39
  • 67
  • so, what about this? http://stackoverflow.com/a/15840257/3960528 He is proving with the source code. – xyz Sep 16 '14 at 21:34
  • Thanks I will accept it..But I did not understand "This is a one time deal and does not affect performance in any meaningful way" How can toy tell this? – xyz Sep 16 '14 at 21:43
  • 1
    @logx It is stated in the method description it is used as part of the inflation process. This process translates the XML to usable Java objects and only needs to be done once per View creation. – Captain Giraffe Sep 16 '14 at 21:45
1

Until the delay in responding to a button click reaches about 1/10th of a second, humans perceive it as instantaneous, so optimizing reflection out of a button click response doesn't matter.

You should not worry about this kind of issue so that optimization effort can focus on the code where there is a measurable performance problem.

x-code
  • 2,940
  • 1
  • 18
  • 19