gpt4 book ai didi

java - 基于用户偏好的调用方法,更快/更好

转载 作者:行者123 更新时间:2023-11-29 06:44:13 25 4
gpt4 key购买 nike

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

案例一:

int userSetting = 1;
Method method = Class.getDeclaredMethod("Method" + userSetting);
method.invoke();


案例二:

 int userSetting = 1;
switch(userSettings) {
case 0:
Method0();
break;
case 1:
Method1();
break;
...
...
}


案例三:

int userSetting = 1;
if(userSetting == 0){
Method0();
} else if(userSetting == 1){
Method1();
} else....

还有:

  • 你认为一个人即使慢一点也比其他人更好?如果是,为什么?
  • 还有另一种方法更好/更快...请告诉我们。

谢谢

最佳答案

选项 1 使用 reflection ,因此可能会更慢,如 javadoc 所示:

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.

然而,维护此选项比维护选项 2+3 更容易。

我建议您使用一个完整的不同的选项:使用strategy design pattern .与替代方案相比,它更有可能更快、更易读。

关于java - 基于用户偏好的调用方法,更快/更好,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7784358/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com