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

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

问题描述

担心我的网络应用程序的性能,我想知道哪个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 块粘在一起或其大小不可预测,那么你可能会高度考虑一个开关声明。

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 <中的所有实现/ code>。您可以静态或动态地执行此操作:

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 / else 切换这样的事情(留下无效的支票,如无效指针):

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

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

可能更小于if / else 切换,但代码至少可以更好地维护。

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

当您谈论网络应用时,您可以使用 HttpServletRequest#getPathInfo() 作为操作键(最终写一些代码,在循环中将pathinfo的最后一部分分开,直到找到一个动作)。你可以在这里找到类似的答案:

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:

  • Using a custom Servlet oriented framework, too many servlets, is this an issue
  • Java Front Controller

如果您一般担心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天全站免登陆