对于 Android 事件,为什么 switch 语句比 if-else 链更常见?

发布于 2024-10-13 10:00:10 字数 825 浏览 5 评论 0原文

当为 Android 开发时,switch 语句是否比 if-else 链更有效? switch 语句需要更多行代码,但从轶事证据来看,它似乎在 Android 应用程序中更常用。

下面的示例使用 case 语句和 if-else 链说明了相同的编程结构。 switch 语句需要 10 行,而 if-else 链需要 7 行。

Case 语句

public void onClickWithSwitch(View v) {
   switch(v.getId()) {
       case R.id.buttonA:
           buttonA();
           break;
       case R.id.buttonB:
           buttonB();
           break;
       case R.id.buttonC:
           buttonC();
   }
}

If-else 链

public void onClickWithIf(View v) {
   int id = v.getId();
   if(id == R.id.buttonA)
       buttonA();
   else if (id == R.id.buttonB)
       buttonB();
   else if (id == R.id.buttonC)
       buttonC();
}

为什么 switch 比 if-else 链更常见?与 if-else 链相比,switch 语句是否能提供更好的性能?

When developing for Android is a switch statement more efficient than an if-else chain? A switch statement takes more lines of code, but looking at anecdotal evidence seems to be the more commonly used in Android applications.

The examples below illustrate the same programming construct with a case statement and if-else chain. The switch statement requires 10 lines while the if-else chain requires 7.

Case Statement

public void onClickWithSwitch(View v) {
   switch(v.getId()) {
       case R.id.buttonA:
           buttonA();
           break;
       case R.id.buttonB:
           buttonB();
           break;
       case R.id.buttonC:
           buttonC();
   }
}

If-else chain

public void onClickWithIf(View v) {
   int id = v.getId();
   if(id == R.id.buttonA)
       buttonA();
   else if (id == R.id.buttonB)
       buttonB();
   else if (id == R.id.buttonC)
       buttonC();
}

Why would switch be more common than an if-else chain? Do switch statements offer better performance when compared to if-else chains?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(5

戏蝶舞 2024-10-20 10:00:10

语言具有 switch 语句的原因是允许编译器生成跳转表,如果跳转表很大,则速度会很快,因为在运行时它可以在 O(1) 内到达所需的代码,而不是准时。

仅当存在多种情况并且每种情况下执行的代码不需要太多时间,并且程序在这些代码中花费了很大比例的时间时,它才对速度有帮助。

除此之外,这纯粹是品味问题。

代码行数和速度之间没有关系。重要的是生成的汇编语言代码的类型,我鼓励您熟悉它。

The reason languages have switch statements is to allow the compiler to generate a jump table, which is fast if it's large, because at run-time it can get to the desired code in O(1) rather than O(N) time.

It's only helpful speed-wise if there are many cases and the code to execute in each case does not take much time, and the program spends much percentage of time in this code at all.

Other than that it's purely a matter of taste.

There is no relationship between number of code lines and speed. What matters is the kind of assembly language code that's generated, which I'd encourage you to get familiar with.

鸠书 2024-10-20 10:00:10

除非你的 ifs/cases 序列确实很大,否则我认为这并不重要。有了 switch 语句,就更清楚发生了什么。唯一的缺点是所有的 break 语句以及可能会错过一个语句,但静态分析器应该能够捕获这一点。

最好是由 id 键控的映射或巧妙地使用子类化

Unless your sequence of ifs/cases is truly vast, I don't think it matters. With the switch statement, it's more clear what's going on. The only downside is all the break statements and the potential to miss one, but a static analyzer should catch that.

Best would be a map keyed by the id or some clever use of subclassing

忆梦 2024-10-20 10:00:10

“更高效”是一个模糊的概念,因为衡量它的方法有很多。我想大多数人都会想到执行时间。另一方面,大多数人并没有想到内存效率。具有广泛间隔的测试值的 switch 语句可能会严重占用内存,除非编译器足够聪明,可以将其重新解释为 if-else 链。

对于编程效率还有很多话要说,包括可维护性和可读性。正如 sblundy 所指出的,switch 语句比 if-else 链更能清楚地了解程序员的意图。注释可以抵消这一点,但这需要程序员做更多的工作,并且还存在注释和代码不匹配的风险(特别是在几个维护周期之后)。

我想大多数人都会遵循他们被教导(或被告知遵循)的任何风格,而不会考虑太多。其余时间,我认为关于 switch 与 if-else 的大多数决定都是基于哪一个最符合程序员在生成代码时的想法。

"More efficient" is a vague concept, because there are so many ways to measure it. I suppose most people think of execution time. On the other hand, most people don't think of memory efficiency. A switch statement with widely spaced test values can be a horrible memory hog, unless the compiler is smart enough to re-interpret it as an if-else chain.

There's a lot to be said, as well, for programming efficiency, including maintenance and readability. As sblundy noted, a switch statement can be clearer about the programmer's intent than an if-else chain. Comments can counterbalance that, but that requires more work for the programmer and there's also the risk that the comments and code don't match (particularly after a few maintenance cycles).

I imagine that most people follow whatever style they have been taught (or told to follow), without thinking about it too much. The rest of the time, I think most decisions about switch vs. if-else are based on which one best matches the programmer's thinking at the moment the code is being generated.

御守 2024-10-20 10:00:10

你问:switch语句真的更高效吗?

任何声称对这个问题有明确和普遍答案的人都是胡说八道。只有一种方法可以找出适合您的情况的更快:在您的目标平台上使用正确的微基准测试框架和完整的软件,而不是简化的示例。如果这揭示了可测量且具有统计显着性的差异,我将有兴趣了解它。我怀疑你会发现真正的程序有任何可测量的差异。

因此,我会严格要求可读性。

You asked: Is a switch statement really more efficient?

Anybody claiming to have a definitive and general answer on this question, talks nonsense. There is exactly one way to find out which is faster in your case: Use a proper micro-benchmarking framework on your target plattform with your complete software, not a simplified example. If that reveals a measurable and statistically signifanct difference I'd be interested in hearing about it. I doubt you'll find any measurable difference for a real program.

Therefore, I would strictly go for readability.

爱你是孤单的心事 2024-10-20 10:00:10

当我们讨论这个主题时,没有人提到您应该始终在 switch 语句中有一个 default 行。通常您想引发异常,但至少应该断言和/或记录错误。

这只是很好的基本防御性编程。如果您稍后添加另一个按钮(在本例中),它会提醒您出现编程错误。

While we're on the subject, nobody mentioned that you should always have a default line in switch statement. Usually you want to throw an exception, but at least you should assert and/or log the error.

This is just good basic defensive programming. It alerts you that you have a programming error if you later add another button (in this case).

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文