优化:switch 语句中 case 的顺序重要吗? [英] Optimization: Is the order of cases in a switch statement important?

查看:201
本文介绍了优化:switch 语句中 case 的顺序重要吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

考虑使用您选择的语言(例如 Java、C、C#...)的 switch 语句.当然,如果有fallthroughs,case语句的顺序很重要,但是假设每个case都有一个break,所以顺序是没有语义重要性.

Consider a switch statement in your language of choice (e.g., Java, C, C#...). Of course, the order of case statements is important if there are fallthroughs, but assume that each case has a break, so the order is of no semantic importance.

例如,在考虑优化时,case 语句的顺序是否重要?按升序对案例进行排序更好还是任何排序都没有好处?编译器可能执行哪些优化取决于 case 的顺序.由于任何编译器可能会也可能不会选择此类优化,因此我不想在这里要求特定的语言或编译器.问题是可能会发生什么.

Is the order of case statements important when, for example, considering optimizations? Is it better to sort the cases in ascending order or are there no benefits in any ordering? What optimizations might a compiler perform that might depend on order of cases. Since any compiler might or might not pick such optimizations, I do not want to ask for a specific language or compiler here. The question is about what could possibly happen.

推荐答案

答案不仅取决于语言,还取决于编译器,甚至取决于您选择的编译器设置.我已经看到它在 C++ 中有所不同,具体取决于我选择的 gcc 优化设置.

The answer depends on not only the language, but the compiler, and even on which compiler settings you choose. I've seen it differ in C++ depending on which gcc optimization settings I chose.

这是因为编译器可能会选择将switch语句实现为一系列测试,就像一系列if/else if语句一样,也可能会选择将switch语句实现为跳转表.对于较早的测试,这一系列测试会更快,而无论顺序如何,跳转表通常都同样快.

This is because the compiler may choose to implement the switch statement as a series of tests, just like a series of if / else if statements, or it may choose to implement the switch statement as a jump table. The series of tests will be faster for earlier tests, while the jump table will typically be equally fast irrespective of the order.

如果您的编译器将您的 switch 语句实现为一系列测试 - 并且没有对它们重新排序 - 将更可能的情况提前将导致更快的代码.据我所知,将更可能的情况提前放置通常不会导致代码变慢,因此如果您的代码花费大量时间执行此 switch 语句,那么将更常见的情况提前放置也无妨.

If your compiler is implementing your switch statement as a series of tests - and does not reorder them - putting the more likely cases earlier will result in faster code. As far as I know, putting the more likely cases earlier should not normally result in slower code, so if your code spends a lot of time executing this switch statement, it can't hurt to put the more common cases earlier.

但是,如果您还没有分析您的代码并且您不知道 switch 语句是一个性能问题,那么最好使用对阅读代码的人来说最清晰的顺序来编写 switch 语句.

However, if you haven't profiled your code and you don't know for a fact that the switch statement is a performance problem, it's better to write the switch statement using the order that's clearest for a human being reading the code.

这篇关于优化:switch 语句中 case 的顺序重要吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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