How is the switch performance report implemented or working domestically?

I read somewhere that the switch uses "Binary Search" or some sorting methods to select the right case exactly, and this increases its performance compared to the else-if ladder.

And also, if we give the case that the switch works faster? This is true? Can you add your valuable suggestions on this?

We discussed the same here and planned to publish as a question.

+14
c ++ c gcc switch-statement if-statement
Dec 28 '12 at 9:45
source share
3 answers

In fact, before the compiler, how the switch is executed in the code.

However, I understand that when it is suitable (i.e. relatively dense cases), a transition table is used.

This would mean something like:

 switch(i) { case 0: doZero(); break; case 1: doOne(); case 2: doTwo(); break; default: doDefault(); } 

In the end, everything will be compiled to something like (a terrible pseudo-assembler, but, in my opinion, it should be clear).

 load i into REG compare REG to 2 if greater, jmp to DEFAULT compare REG to 0 if less jmp to DEFAULT jmp to table[REG] data table ZERO ONE TWO end data ZERO: call doZero jmp END ONE: call doOne TWO: call doTwo jmp END DEFAULT: call doDefault END: 

If this is not the case, there are other possible implementations that allow to some extent "better than a sequence of conditional expressions."

+14
Dec 28 2018-12-12T00:
source share

How swtich is implemented depends on what values โ€‹โ€‹you have. For values โ€‹โ€‹close to the range, the compiler usually generates a jump table. If the values โ€‹โ€‹are far apart, it will generate a related branch using something like a binary search to find the correct value.

The order of the switch statements as such does not matter, it will do the same, regardless of whether you have order in ascending, descending or random order - do what matters most with respect to what you want to do.

If nothing else, a switch is usually much easier to read than an if-else sequence.

+8
Dec 28 '12 at 10:05
source share

In some googling I found an interesting link and planned to publish it as an answer to my question. http://www.codeproject.com/Articles/100473/Something-You-May-Not-Know-About-the-Switch-Statem

Comments are welcome.

+1
Dec 28 '12 at 10:01
source share



All Articles