4

I read many times that reflection will slow down the phone performance. How true is this?

For example in my case, I get some parameters from a web service which have the same name as the parameters of a class I have in my android app. so I just set the values of these parameters using java fields and reflection... it doesn't seem to slow down the performance..

can anybody explain to me the fact behind this idea about reflection slowing down performance?

RoflcoptrException
  • 51,941
  • 35
  • 152
  • 200
ccot
  • 1,875
  • 3
  • 36
  • 54
  • Pretty much a duplicate of this: [Java Reflection Performance](http://stackoverflow.com/questions/435553/java-reflection-performance). – eldarerathis Mar 30 '11 at 20:56

2 Answers2

7

Take a look at this question. Basically, you are getting outside of the optimizations that the compiler can perform because reflection happens dynamically.

If you're not making a lot of reflection calls (e.g., it would be bad to do inside the getView of a ListView), you can probably get away with it. It's there to be used, just be judicious about it.

Community
  • 1
  • 1
Brian Cooley
  • 11,622
  • 4
  • 40
  • 39
4

how true is this?

It is slower than not using reflection. It is definitely something you want to avoid in loops or during rapid UI processing (e.g., scrolling a ListView).

i get some parameters from a web service which have the same name as the parameters of a class i have in my android app. so i just set the values of these parameters using java fields and reflection... it doesn't seem to slow down the performance..

It does, though it may not be noticeable to the user in this case.

can anybody explain to me the fact behind this idea about reflection slowing down performance?

See the link provided by @Brian Cooley in his answer. Bear in mind that reflection on Dalvik (the virtual machine in Android) may be slower than reflection on the Java VM -- I am really rather certain it is not faster, at any rate.

Community
  • 1
  • 1
CommonsWare
  • 986,068
  • 189
  • 2,389
  • 2,491
  • thank you for your reply. It makes sense on the UI level that it slows it down. However i am using it in the domain logic layer, where i set the parameters of a class that implement kvmserializable(ksoap2) using reflection, with values that the web services sends to me. I made a separation of concern between the UI and domain logic, so as long as the user is concerned, everything is preloaded for him while using the UI. In my case does it still slow down performance? – ccot Mar 30 '11 at 21:02
  • 2
    @Chadic: By definition, it still slows down performance and uses more battery life. Whether the user will *perceive* any of this is the question. It all depends on how frequently that portion of your code is executed. If it is once every minute or two, and you're only doing a few bits of reflection, it should be fine. If you are doing millions of reflection calls, it will not be fine. – CommonsWare Mar 30 '11 at 21:17