Two days ago I flipped through the lab and saw that the first chapter of deep understanding of computer systems mentioned a problem. Is the switch statement the same as if else? Why? I was very interested in preparing for this.
However, after Google finds that other people's blogs talk about the same thing, let me learn -_-
In short, when the values of the switch statement in the case are relatively concentrated, such as Case 1, case 3, case 4, Case 5..., an address table is constructed,
The address table records the numbers that should be jumped in sequence. During JMP, the switch () variable is subtracted from the minimum value to obtain the offset from the address table, then, use the corresponding offset address as
Destination value. O (e) complexity.
If the segments are sparse,
1) if the number of cases is small, CMP value, variable; je label x
(In fact, even the switch with the least optimization is more efficient than if Else.Code, You will see that if is not set up to the branch of else if, you need to perform a CMP
The reason is that the switch value is mutually exclusive and a simple int, while the hidden condition of if (a) else if (B) is if (a) if (! A & B) complicated ...)
2) if there are many cases, sort the variables in the case, and then compare the CMP values in the order of binary search to reduce the average number of comparisons.
After understanding it, I felt that the grandfather who wrote the compiler had made a fortune ......
I did some experiments myself, so I am too lazy to paste the assembly code. I have them online. Let's send them to a portal.
Http://tianlihu.iteye.com/blog/400283