Let say I have a switch statement as below
switch(alphabet) { case "f": //do something break; case "c": //do something break; case "a": //do something break; case "e": //do something break; }
Now suppose I know that the frequency of having Alphabet
e is highest followed by a, c and f respectively. So, I just restructured the case
statement order and made them as follows:
switch(alphabet) { case "e": //do something break; case "a": //do something break; case "c": //do something break; case "f": //do something break; }
Will the second switch
statement be faster than the first switch
statement? If yes and if in my program I need to call this switch
statement say many times, will that be a substantial improvement? Or if not in any how can I use my frequency knowledge to improve the performance?
Answer. Switch case variables can have only int and char data type. So float or no data type is allowed. In this ch can be integer or char and cannot be float or any other data type.
As it turns out, the switch statement is faster in most cases when compared to if-else , but significantly faster only when the number of conditions is large.
Execution of the switch statement body begins at the first statement in or after the matching labeled-statement . Execution proceeds until the end of the body, or until a break statement transfers control out of the body.
Rules for switch statement in C language 1) The switch expression must be of an integer or character type. 2) The case value must be an integer or character constant. 3) The case value can be used only inside the switch statement. 4) The break statement in switch case is not must.
Not so much that you should be concerned. It's certainly not something that can be predicted.
With string case labels, the compiler actually uses an internal hash table that maps the strings to indexes in a jump-table. So the operation is actually O(1) - independent of the number of labels.
For integer labels, then I believe the actual code that is generated depends on the number of labels and whether the numbers are consecutive (or "almost" consecutive). If they're consecutive (1, 2, 3, 4, ...) then they'll just be transformed into a jump table. If there's a lot of them, then the Hashtable+jump table (like with strings) will be used. If there's only a few labels and they're not table to be immediately transformed into a jump table, only then will be transformed into a series of if..then..else statements.
In general, though, you should write code so that you can read it, not so that the compiler can produce "faster" code.
(Note my description above is an implementation detail of how the C# compiler works internally: you shouldn't rely on it always working like that -- in fact, it might not even work exactly like that now, but at least it's the general idea).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With