Raw Results
This table shows the timings for the empty loop, if statement and switch statement for one billion iterations rounded to the nearest millisecond. The two columns show the results for the loops where matching of the comparison value occurs and for the non-matching tests.
Adjusted Results
This second table shows the results for the two key test types, adjusted to remove the delay created by the looping mechanism.
Conclusion
The results show that the switch statement is faster to execute than the if-else-if ladder. This is due to the compiler’s ability to optimise the switch statement. In the case of the if-else-if ladder, the code must process each if statement in the order determined by the programmer. However, because each case within a switch statement does not rely on earlier cases, the compiler is able to re-order the testing in such a way as to provide the fastest execution.
This table shows the timings for the empty loop, if statement and switch statement for one billion iterations rounded to the nearest millisecond. The two columns show the results for the loops where matching of the comparison value occurs and for the non-matching tests.
Matching | Non-Matching | |
Empty Loop | 27.3s | 5.0s |
Switch Statement | 43.0s | 5.0s |
If Statement | 48.0s | 5.1s |
This second table shows the results for the two key test types, adjusted to remove the delay created by the looping mechanism.
Matching | Non-Matching | |
Switch Statement | 15.7s | 0.0s |
If Statement | 20.7s | 0.1s |
The results show that the switch statement is faster to execute than the if-else-if ladder. This is due to the compiler’s ability to optimise the switch statement. In the case of the if-else-if ladder, the code must process each if statement in the order determined by the programmer. However, because each case within a switch statement does not rely on earlier cases, the compiler is able to re-order the testing in such a way as to provide the fastest execution.
No comments:
Post a Comment