Switch statement implementation

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.