Why is reflection slow?

Viewed 9534

Is it because we should load class (by string for example), create instance, then search for appropriate method, pack parameters, and then just invoke method? So most time is spent on these operations instead of explicit method invocation on an object, right?

5 Answers

When you call a method, you need to know if you're doing so with valid arguments, on a valid object, what the return type is, and what bytecode to execute. When the exact method is specified in code, java can quickly figure this stuff out and move on to actually executing the method.

When you do this with reflection, you know a lot less. Since the method to be invoked wasn't specified in the code, none of this can be done beforehand, and the VM has to do things at run time that are far more complex and processor intensive.

Polymorphic method calls can be though of as somewhere between these two extremes. You don't know what method to invoke until run time, but at least you can be sure of the method's name, arguments, and return type. The more you know about what method to execute, the more Java can avoid doing at run time.

This proves that reflection is slower, but not that it is actually "slow." If you need reflection or polymorphic methods, use them, and save the judgement of what is "slow" for later.

According to Oracle documentations

Reflection is slower Because it involves types that are dynamically resolved, certain Java virtual machine optimizations can not be performed. Consequently, reflective operations have slower performance than their non-reflective counterparts, and should be avoided in sections of code which are called frequently in performance-sensitive applications.

Related