Implement a switch statement

Two days before the open book in the lab, see the "in-depth understanding of computer systems," the beginning of a chapter mentions a problem, switch statements and efficiency if else like it? Why? Suddenly sprouted a lot of interest, prepare a practice.

But google it and found inside someone else's blog talking about it, I already learn it -_-

Briefly, in the case where the switch statement values ​​are concentrated inside the case, as case 1, case 3, case 4, case 5 ... constructs a table address,

Address table which records the sequentially should jump labels, jmp time, it will switch () subtracting the minimum value of the variable, which is acquired than offset address table, then the corresponding offset address as the jmp

Destination value. O (e) the complexity of ah.

If the division sparse words,

1) relatively small number case, directly cmp value, variable; je Label X

(In fact, even the least of this optimization switch, efficiency is still higher than if else, if else compiled code, you will see, if not established branch else if transferred, but also to conduct a cmp

The reason is because the value of the switch are mutually exclusive, simple int, and if (a) else if (B) is concealed condition if (a) if (! A && B) complex. . . )

2) number of more case, the variable ordering of the entire case, cmp is then sequentially compared in accordance with a binary search sequence. Reduce the average number of comparisons.

 

After understand, I think to write compiler grandfather bunker ......

 

And he did a little experiment, too lazy to paste up the assembly code, online, give it a portal

http://tianlihu.iteye.com/blog/400283

Reproduced in: https: //www.cnblogs.com/bluesea147/archive/2012/08/03/2621509.html

Guess you like

Origin blog.csdn.net/weixin_34161083/article/details/94283062