Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
329 views
in Technique[技术] by (71.8m points)

c++ - How Switch case Statement Implemented or works internally?

I read somewhere that the switch statement uses "Binary Search" or some sorting techniques to exactly choose the correct case and this increases its performance compared to else-if ladder.

And also if we give the case in order does the switch work faster? is it so? Can you add your valuable suggestions on this?

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

It's actually up to the compiler how a switch statement is realized in code.

However, my understanding is that when it's suitable (that is, relatively dense cases), a jump table is used.

That would mean that something like:

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

Would end up getting compiled to something like (horrible pseudo-assembler, but it should be clear, I hope).

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 that's not the case, there are other possible implementations that allow for some extent of "better than a a sequence of conditionals".


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...