Java 中 if/else 与 switch 语句的相对性能差异是什么? [英] What is the relative performance difference of if/else versus switch statement in Java?

查看:26
本文介绍了Java 中 if/else 与 switch 语句的相对性能差异是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

担心我的 Web 应用程序的性能,我想知道if/else"或 switch 语句中哪一个在性能方面更好?

Worrying about my web application's performances, I am wondering which of "if/else" or switch statement is better regarding performance?

推荐答案

那是微优化和过早优化,这是邪恶的.而是担心相关代码的可读性和可维护性.如果有两个以上的 if/else 块粘在一起或者其大小不可预测,那么您可能会高度考虑使用 switch 语句.

That's micro optimization and premature optimization, which are evil. Rather worry about readabililty and maintainability of the code in question. If there are more than two if/else blocks glued together or its size is unpredictable, then you may highly consider a switch statement.

或者,您也可以获取多态.首先创建一些接口:

Alternatively, you can also grab Polymorphism. First create some interface:

public interface Action { 
    void execute(String input);
}

并在某些Map 中掌握所有实现.您可以静态或动态执行此操作:

And get hold of all implementations in some Map. You can do this either statically or dynamically:

Map<String, Action> actions = new HashMap<String, Action>();

最后用这样的东西替换 if/elseswitch(把空指针之类的琐碎检查放在一边):

Finally replace the if/else or switch by something like this (leaving trivial checks like nullpointers aside):

actions.get(name).execute(input);

可能if/elseswitch 微慢,但代码的可维护性至少要好得多.

It might be microslower than if/else or switch, but the code is at least far better maintainable.

当您谈论 Web 应用程序时,您可以使用 HttpServletRequest#getPathInfo() 作为动作键(最终编写更多代码以在循环中拆分路径信息的最后部分,直到动作被发现).你可以在这里找到类似的答案:

As you're talking about webapplications, you can make use of HttpServletRequest#getPathInfo() as action key (eventually write some more code to split the last part of pathinfo away in a loop until an action is found). You can find here similar answers:

如果您通常担心 Java EE Web 应用程序的性能,那么您可能会发现 这篇文章 也很有用.与仅(微)优化原始 Java 代码相比,还有其他一些领域可以更多获得性能提升.

If you're worrying about Java EE webapplication performance in general, then you may find this article useful as well. There are other areas which gives a much more performance gain than only (micro)optimizing the raw Java code.

这篇关于Java 中 if/else 与 switch 语句的相对性能差异是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆