the*_*ish 1 c++ performance if-statement
我正在阅读C++:如何编程, Paul 和 Harvey Deitel 的第九版,我在第 114 页发现了一些让我感到困惑的东西。
书中给出了示例代码:
if ( studentGrade >= 90 ) // 90 and above gets "A"
cout << "A";
else
if ( studentGrade >= 80 ) // 80-89 gets "B"
cout << "B";
else
if ( studentGrade >= 70 ) // 70-79 gets "C"
cout << "C";
else
if ( studentGrade >= 60 ) // 60-69 gets "D"
cout << "D";
else // less than 60 gets "F"
cout << "F";
Run Code Online (Sandbox Code Playgroud)
这本书接着说:
大多数程序员将前面的语句写为:
if ( studentGrade >= 90 ) // 90 and above gets "A"
cout << "A";
else if ( studentGrade >= 80 ) // 80-89 gets "B"
cout << "B";
else if ( studentGrade >= 70 ) // 70-79 gets "C"
cout << "C";
else if ( studentGrade >= 60 ) // 60-69 gets "D"
cout << "D";
else // less than 60 gets "F"
cout << "F";
Run Code Online (Sandbox Code Playgroud)
除了间距和缩进之外,这两种形式是相同的,编译器会忽略它们。后一种形式很受欢迎,因为它避免了代码向右的深度缩进,这会强制换行。
在其下方有一个标记为Performance Tip 4.1的框:
嵌套 if...else 语句的执行速度比一系列单选 if 语句快得多,因为在满足其中一个条件后可能会提前退出。
我不太明白这一点,因为(我假设“一系列单选 if 语句”意味着第二个代码示例,使用if...else if相同的缩进;这种风格非常流行)从我对 C 的理解来看和 C++,当一个if语句或以下else if语句之一被测试为真时,其余的else if语句甚至没有被测试,它们只是被跳过。那不就和提前退出一样吗?此外,这本书说,就编译器而言,这两种形式是相同的,为什么一种会优于另一种?
书中没有显示“一系列单选 if 语句”。这将类似于您展示的两个代码示例,但没有else关键字。但是,您必须添加一些代码以排除较早的情况。
if ( studentGrade >= 90 ) // 90 and above gets "A"
cout << "A";
if (studentGrade < 90 && studentGrade >= 80 ) // 80-89 gets "B"
cout << "B";
if (studentGrade < 80 && studentGrade >= 70 ) // 70-79 gets "C"
cout << "C";
if (studentGrade < 70 && studentGrade >= 60 ) // 60-69 gets "D"
cout << "D";
if (studentGrade < 60) // less than 60 gets "F"
cout << "F";
Run Code Online (Sandbox Code Playgroud)
除了必须运行您知道将是错误的测试(在输出成绩之后)之外,后面的测试更加复杂,并且在这些扩展测试中很容易出错(要么忘记排除前面的情况,要么不排除)正确键入排除项)。所有这些额外的代码也使代码在阅读时更难理解。
所以使用if else链对于性能、代码可读性和代码维护来说更好。