基于用户偏好的呼叫方法,更快/更好

Bra*_*ash 1 java optimization

我们有X方法,我们喜欢调用一个相对于用户设置的方法,以下哪个运行得更快?

情况1:

int userSetting = 1;
Method method = Class.getDeclaredMethod("Method" + userSetting);
method.invoke();
Run Code Online (Sandbox Code Playgroud)


案例2:

 int userSetting = 1;
 switch(userSettings) {
     case 0:
         Method0();
     break;
     case 1:
         Method1();
     break;
     ...
     ...
 }
Run Code Online (Sandbox Code Playgroud)


案例3:

int userSetting = 1;
if(userSetting == 0){
    Method0();
} else if(userSetting == 1){
    Method1();
} else....
Run Code Online (Sandbox Code Playgroud)

也:

  • 你认为即使速度较慢也是其他人更好的做法?如果是,为什么?
  • 另一种方式是女巫更好/更快......请告诉我们.

谢谢

ami*_*mit 5

选项1使用反射,因此可能会更慢,因为javadocs指示:

Performance Overhead
    Because reflection 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.
Run Code Online (Sandbox Code Playgroud)

但是,更容易维护此选项,然后选项2 + 3.

我建议你使用完全不同的选项:使用策略设计模式.与替代方案相比,它更可能更快,更易读.