gpt4 book ai didi

java - Java 中的 Switch 语句与 If 语句

转载 作者:行者123 更新时间:2023-12-01 06:34:48 25 4
gpt4 key购买 nike

Herbert Schildt 在“完整引用”中 - 第 5 章:

A switch statement is usually more efficient than a set of nested ifs.

When the compiler compiles a switch statement , it inspects each of the case constants and creates a "Jump Table" that it will use for selecting the path of execution depending on the value of the expression. Therefore, if you need to select among a large group of values, a switch statement will run much faster than the equivalent logic coded using a sequence of if-elses. The compiler can do this because it knows that the case constants are all the same type and simply must be compared for equality with the switch expression. The compiler has no such knowledge of a long list of if expressions.

  1. 他所说的术语“JUMP TABLE”是什么意思?

  2. Switch 与 if 语句的不同之处在于,switch 只能测试是否相等,而 if 可以评估任何类型的 boolean 表达式。如果 switch(expression) 与任何 case 常量都不匹配,则意味着它位于 default case 内。这不是不平等的情况吗?这让我觉得 switchif 之间没有那么大的区别。

  3. 从同一本书的摘录中,他写道:

    An if-then-else statement can test expressions based on ranges of values or conditions, whereas a switch statement tests expressions based only on a single integer, enumerated value, or String object.

    这不是让 ifswitch 更强大吗?

  4. 我曾在 Core Java 的不同项目中工作过,但从未觉得有必要使用 switch 语句,也没有看到其他同事使用它。一次也没有。为什么功能更强大的 switch 控制语句在可用性方面无法领先于 if

最佳答案

1) 编译器为每个 case 语句创建一个包含一行的表,其中 case 条件是键,代码块是值。当代码中执行 switch 语句时,可以通过 case block 的键直接访问 case block 。在嵌套的 if block 中,您需要检查并执行每个条件,然后才能找到输入条件代码块的正确条件。

将其视为哈希表(用于 switch case)与线性链表(用于嵌套 if 语句),并比较是时候查找特定值了。表的查找时间为O(1)(只需一次操作即可获取),而链表中的查找时间为O(n)(查看每一个操作)直到您找到合适的为止)。

3) 是的,if 语句可以使用得更灵活,表达更多,但如果您想在不同代码块之间切换以获得不同值的列表switch block 执行速度更快且更具可读性。

4) 你永远不需要使用switch,因为嵌套的if可以表达相同的意思,但在某些情况下它更优雅。但由于很少有机会使用它,程序员会忘记它,甚至在更适合的地方也不使用它。

2)从其他点的答案中提取差异。

关于java - Java 中的 Switch 语句与 If 语句,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25790180/

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