Tuesday, March 2, 2010

Reflection is bad

My personal opinion: "Reflection is evil and should be avoided whenever it's possible"

List of reasons why reflection is bad:
  1. It is hack of compiler. Compiler is not able to check code consistency if you use reflection. Problems with incorrect names or types will popup only at runtime
  2. Automatic development tools are not able to work with reflections code. E.g. in Eclipse instead of Java search for method names, types declarations or references you have only plain text search. All automatic refactoring or code analysis tools became useless.
  3. It's difficult to debug reflections code.
  4. Reflection complicates understanding and navigation in code. For regular call of method I can get Java help popup or go to method body (just by Ctr+click). It's not possible for the method which is called by reflection. Code assistant doesn't work also. It's like writing code in the Notepad.
  5. For me all above reasons are sufficient for avoiding refactoring. But there is one more – significant performance penalty. I have created a simple test. It shows that method invocation by reflection is 60 times slower than regular! Even with some optimization (if we call the same method multiple times) it's 5 times slower.
Here is code of my performance test:
Test ouput:
direct call time = 31 msec. reflection time = 1797 msec. reflection (optimized) time = 157 msec.

Discussions on Sun Java forum
More Discussions on Sun Java forum
More Discussions on Sun Java forum
"A general rule of thumb: if your design uses reflection, then rethink your design; you can probably solve the problem better with cleaner decomposition of classes, better polymorphism, etc."

A good discussion on reflection (with actual statistics) can be found here
Here is small article of Christian Cryder


If you think this is directed to anyone in particular: If the suit fits wear it #LOL

No comments:

Post a Comment