我们有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)
也:
谢谢
选项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.
我建议你使用完全不同的选项:使用策略设计模式.与替代方案相比,它更可能更快,更易读.
归档时间: |
|
查看次数: |
97 次 |
最近记录: |