Is There Any Significant Difference Between Using If/Else and Switch-Case in C#

Is there any significant difference between using if/else and switch-case in C#?

SWITCH statement only produces same assembly as IFs in debug or compatibility mode. In release, it will be compiled into jump table (through MSIL 'switch' statement)- which is O(1).

C# (unlike many other languages) also allows to switch on string constants - and this works a bit differently. It's obviously not practical to build jump tables for strings of arbitrary lengths, so most often such switch will be compiled into stack of IFs.

But if number of conditions is big enough to cover overheads, C# compiler will create a HashTable object, populate it with string constants and make a lookup on that table followed by jump. Hashtable lookup is not strictly O(1) and has noticeable constant costs, but if number of case labels is large, it will be significantly faster than comparing to each string constant in IFs.

To sum it up, if number of conditions is more than 5 or so, prefer SWITCH over IF, otherwise use whatever looks better.

C# if else vs if or vs switch case

In some cases, an equivalent switch statement is slower than an if-statement or chain of if-statements. Using frequency heuristics, you can optimize a fast path with an if-statement in many programs.

See this Link you will find two different comparisons

http://www.dotnetperls.com/if-switch-performance

Is else if faster than switch() case ?

For just a few items, the difference is small. If you have many items you should definitely use a switch.

If a switch contains more than five items, it's implemented using a lookup table or a hash list. This means that all items get the same access time, compared to a list of if:s where the last item takes much more time to reach as it has to evaluate every previous condition first.

When to use If-else if-else over switch statements and vice versa

As with most things you should pick which to use based on the context and what is conceptually the correct way to go. A switch is really saying "pick one of these based on this variables value" but an if statement is just a series of boolean checks.

As an example, if you were doing:

int value = // some value
if (value == 1) {
doThis();
} else if (value == 2) {
doThat();
} else {
doTheOther();
}

This would be much better represented as a switch as it then makes it immediately obviously that the choice of action is occurring based on the value of "value" and not some arbitrary test.

Also, if you find yourself writing switches and if-elses and using an OO language you should be considering getting rid of them and using polymorphism to achieve the same result if possible.

Finally, regarding switch taking longer to type, I can't remember who said it but I did once read someone ask "is your typing speed really the thing that affects how quickly you code?" (paraphrased)

If vs. Switch Speed

The compiler can build jump tables where applicable. For example, when you use the reflector to look at the code produced, you will see that for huge switches on strings, the compiler will actually generate code that uses a hash table to dispatch these. The hash table uses the strings as keys and delegates to the case codes as values.

This has asymptotic better runtime than lots of chained if tests and is actually faster even for relatively few strings.

Case vs If Else If: Which is more efficient?

It seems that the compiler is better in optimizing a switch-statement than an if-statement.

The compiler doesn't know if the order of evaluating the if-statements is important to you, and can't perform any optimizations there. You could be calling methods in the if-statements, influencing variables. With the switch-statement it knows that all clauses can be evaluated at the same time and can put them in whatever order is most efficient.

Here's a small comparison:

http://www.blackwasp.co.uk/SpeedTestIfElseSwitch.aspx

If else if or Switch case

For both readability and sense use a switch statement instead of loads of IF statements.

The switch statement is slightly faster though:

http://www.blackwasp.co.uk/SpeedTestIfElseSwitch.aspx (first hit on Google)

The compiler can optimise the switch statement so use that if you have more than, I would say, 3 or 4 different cases

Avoid if-else or switch-case statements for deciding

You can build some kind of map:

Upd.

According to your comment:

    // somewhere this class is defined in your code
class ParamInfo {}

private readonly Dictionary<Type, Action<ParamInfo>> typeToControlsInsertActionMap;

public MyForm()
{
typeToControlsInsertActionMap = new Dictionary<Type, Action<ParamInfo>>
{
{ typeof(string), InsertOneTextBox },
{ typeof(int), InsertTwoTextBoxs },
{ typeof(decimal), InsertTwoTextBoxs },

// etc.
};
}

private void InsertOneTextBox(ParamInfo paramInfo) {}
private void InsertTwoTextBoxs(ParamInfo paramInfo) {}

Here Action<ParamInfo> is a delegate, which inserts appropriate controls, depending on property type:

var paramInfo = // ...
var propertyType = // ...

typeToControlsInsertActionMap[propertyType](paramInfo);

Note, that you shouldn't check type name in your case. Use typeof operator instead.



Related Topics



Leave a reply



Submit