Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

java: is it more efficient a switch or a reflection?

From a jsp I get a string that I could use for a switch

switch(value)
case 0: method0(); break;
case 1: method1(); break;
...

or for a reflection:

c.getMethod("method"+value, parameter);
...

Which approach is more efficient?

like image 957
Accollativo Avatar asked Mar 25 '26 10:03

Accollativo


2 Answers

Reflection is definitely not faster, as it has to go through additional layers.

However, using reflection for such a task would be the wrong way, as it makes the code harder to maintain and doesn't serve a real purpose which reflection is designed for.

like image 56
Devolus Avatar answered Mar 27 '26 22:03

Devolus


If you have fixed number of methods and you are just lazy to type 1000 different cases, then you'd definitely use switch, because that statement is highly optimized on JVM bytecode level.

If you have an indefinite number of methods, you could use reflection (probably you don't have any other choices). Still you can speed up the process by caching the Method instances you get from getMethod().

Note that passing arguments via reflection always creates extra arrays of Classes and Objects.

like image 26
gaborsch Avatar answered Mar 27 '26 23:03

gaborsch



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!