Alex Rivera | Logout

How Switch case Statement Implemented or works internally?

Asked 2012-12-28T09:45:52.023
30

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.

Edit
Report

1 Answer

14

How swtich is implemented depends on what values you have. For values that are close in range, the compiler will generally generate a jump table. If the values are far apart, it will generate a linked branch, using something like a binary search to find the right value.

The order of the switch statements as such doesn't matter, it will do the same thing whether you have the order in ascending, descending or random order - do what makes most sense with regard to what you want to do.

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

answered 2012-12-28T10:05:01.100

Your Answer