- RISE FROM THE ASHES – Sanjib Nandi - November 1, 2021
- साथ में मेरे दोस्त खड़े थे - August 1, 2021
- BenchmarkDotNet: Advanced Features - June 20, 2021
Code used in this exercise is available here on GitHub for experiment.
In our C# programming life, we use If-Else if, Switch case and If conditional statements frequently. If you just start using them and putting conditions in a random order, please wait, this 3 minutes read will change your approach and by the end of this article, you will have full proof answers to the following question –
- Is there any performance difference among them?
- Which one is better to use?
- Does the ordering of conditions impact the performance? If Yes, How?
- When to use what?
If these questions are confusing to you, don’t worry. We will walk through the scenario and do a comparative study of their performances and demystify the secrets.
Approach
Scenario –
Here we are going to decide if the passed day is Weekday or Weekend. For this we will be using If-else if, Switch case and Simple If conditions.
Analysis –
We will put the true condition in the beginning and then in the last in another method for each conditional statement.
In order to evaluate the performance in each case, we are going to run this 100,000 times and then this loop for 1000 times and taking an average of this. Again, we will be running the whole process for 5 times and I will share the findings and results. This has been done in this code. The complete code is available on GitHub for more experiment.
static void Main(string[] args)
{
Stopwatch sw = new Stopwatch();
for (int x = 0; x < 5; x++)
{
for (int i = 0; i < loop; i++)
{
sw.Start();
DecideDayIfFirst();
DecideDayIfLast();
DecideDayIfSimpleFirst();
DecideDayIfSimpleLast();
DayComparisonSwitchFirst();
DayComparisonSwitchLast();
sw.Stop();
ticksSum = ticksSum + sw.ElapsedTicks;
sw.Reset();
}
Console.WriteLine($"{ticksSum / loop}");
}
Console.ReadLine();
}
I am using ticks here to evaluate the time, as I have considered memory to be available and time is more precious.
If Condition
This is the basic If condition where we will have multiple if conditions like this –
Code Sample
static void DecideDayIfSimpleFirst()
{
string day = "Saturday";
string dayType = string.Empty;
for (int i = 0; i < SampleSize; i++)
{
if (day == "Saturday")
{
dayType = "Weekend";
}
if (day == "Sunday")
{
dayType = "Weekend";
}
if (day == "Monday")
{
dayType = "Weekday";
}
if (day == "Tuesday")
{
dayType = "Weekday";
}
if (day == "Wednesday")
{
dayType = "Weekday";
}
if (day == "Thursday")
{
dayType = "Weekday";
}
if (day == "Friday")
{
dayType = "Weekday";
}
else
{
dayType = "Something Wrong !!!";
}
}
}
static void DecideDayIfSimpleLast()
{
string day = "Saturday";
string dayType = string.Empty;
for (int i = 0; i < SampleSize; i++)
{
if (day == "Sunday")
{
dayType = "Weekend";
}
if (day == "Monday")
{
dayType = "Weekday";
}
if (day == "Tuesday")
{
dayType = "Weekday";
}
if (day == "Wednesday")
{
dayType = "Weekday";
}
if (day == "Thursday")
{
dayType = "Weekday";
}
if (day == "Friday")
{
dayType = "Weekday";
}
if (day == "Saturday")
{
dayType = "Weekend";
}
else
{
dayType = "Something Wrong !!!";
}
}
}
Result
More data about this analysis is available with the code repository. Unit of measurement is elapsed ticks from the stopwatch. Since Multiple if evaluates all expressions so we don’t see much difference in their performance.
When true condition is in the First (A) | When true condition is in the Last (B) | Performance (B/A) |
5315 | 5425 | 1.020696 |
10398 | 10696 | 1.028659 |
15622 | 15924 | 1.019332 |
20843 | 21144 | 1.014441 |
26015 | 26307 | 1.011224 |
If-Else if Condition
For this we have following code –
Code Sample
static void DecideDayIfFirst()
{
string day = "Saturday";
string dayType = string.Empty;
for (int i = 0; i < SampleSize; i++)
{
if (day == "Saturday")
{
dayType = "Weekend";
}
else if (day == "Sunday")
{
dayType = "Weekend";
}
else if (day == "Monday")
{
dayType = "Weekday";
}
else if (day == "Tuesday")
{
dayType = "Weekday";
}
else if (day == "Wednesday")
{
dayType = "Weekday";
}
else if (day == "Thursday")
{
dayType = "Weekday";
}
else if (day == "Friday")
{
dayType = "Weekday";
}
else
{
dayType = "Something Wrong !!!";
}
}
}
static void DecideDayIfLast()
{
string day = "Saturday";
string dayType = string.Empty;
for (int i = 0; i < SampleSize; i++)
{
if (day == "Sunday")
{
dayType = "Weekend";
}
else if (day == "Monday")
{
dayType = "Weekday";
}
else if (day == "Tuesday")
{
dayType = "Weekday";
}
else if (day == "Wednesday")
{
dayType = "Weekday";
}
else if (day == "Thursday")
{
dayType = "Weekday";
}
else if (day == "Friday")
{
dayType = "Weekday";
}
else if (day == "Saturday")
{
dayType = "Weekend";
}
else
{
dayType = "Something Wrong !!!";
}
}
}
Results
More data about this analysis is available with the code repository. Unit of measurement is elapsed ticks from the stopwatch.
When true in First (A) | When true in Last (B) | Performance (B/A) |
942 | 5364 | 5.6942675 |
1768 | 10489 | 5.9326923 |
2481 | 15670 | 6.3160016 |
3159 | 20765 | 6.5732827 |
3825 | 25886 | 6.7675817 |
Switch Case
With the switch case also, we will be doing the same test as follows
Code Sample
static void DayComparisonSwitchFirst()
{
string dayType = string.Empty;
string day = "Saturday";
for (int i = 0; i < SampleSize; i++)
{
switch (day)
{
case "Saturday":
dayType = "Weekend";
break;
case "SundayS":
dayType = "Weekend";
break;
case "Monday":
dayType = "Weekday";
break;
case "Thursday":
dayType = "Weekday";
break;
case "Tuesday":
dayType = "Weekday";
break;
case "Wednesday":
dayType = "Weekday";
break;
case "Friday":
dayType = "Weekday";
break;
default:
break;
}
}
}
static void DayComparisonSwitchLast()
{
string dayType = string.Empty;
string day = "Saturday";
for (int i = 0; i < SampleSize; i++)
{
switch (day)
{
case "Sunday":
dayType = "Weekend";
break;
case "Monday":
dayType = "Weekday";
break;
case "Thursday":
dayType = "Weekday";
break;
case "Tuesday":
dayType = "Weekday";
break;
case "Wednesday":
dayType = "Weekday";
break;
case "Friday":
dayType = "Weekday";
break;
case "Saturday":
dayType = "Weekend";
break;
default:
break;
}
}
}
Result
More data is available with code repository In Switch case, we can see there is not much difference in their performances on the basis of order. It is almost the same.
First case is true (A) | Last case is true (B) | Diff (B/A) |
9142 | 9137 | .9994531 |
17945 | 17833 | .9937587 |
26599 | 26957 | 1.013459 |
35236 | 35711 | 1.013481 |
43943 | 44327 | 1.008739 |
Conclusion
With the above study, we can easily conclude the following and use them in our assignment –
Placement order of “true condition” impacts the performance
- As we saw here, we compared the true with the extreme scenario and figured out the impact on performance. Hence try to place the conditions in order of their frequency.
- We see here, if-else if has the biggest performance difference (up to 6-7 times) while Switch case doesn’t differ much and it is almost the same with the placement of condition.
- Having “Multiple If conditions” impact the most as it evaluates all conditions. If-else if doesn’t evaluate once it finds the true condition and Switch case evaluates only the true case.
When to use What?
- When we are certain about the frequency and order of condition, use if-else if.
- When we don’t know the frequency and it could be random, still if-else if has better performance. See the ticks elapsed in last condition If-else if vs first condition switch case from the above table.
- Do NOT use multiple If statements, as it will impact the performance as it will evaluate the expression again and again even after true condition, is met. Hence We don’t see much difference in performance based on order. Similarly, we don’t see a performance difference with Switch but if we compare Switch with multiple if, multiple If gets an edge.
- So preference of C# Conditional Statements goes in this order – #1 – If- Else If -> #2 Multiple If -> #3 Switch case.
- If there are not many conditions and they are straightforward then Switch case can be considered as it provides better readability over either of the If conditions and on performance front doesn’t impose a huge penalty.
- If we need to use Switch case for pattern matching (as we have done in this example) and if there are too many scenarios then dictionary with the query can be a better contestant for this scenario.
- When we have multiple OR expressions in conditional expressions the Switch can be more readable than If-else if. The example used in this article can be re-written and we will
analyse the performance as well.
static void DayComparisonMultiORIf()
{
string day = "Friday";//"Saturday";
string dayType = string.Empty;
for (int i = 0; i < SampleSize; i++)
{
if (day == "Saturday" || day == "Sunday")
{
dayType = "Weekend";
}
else if (day == "Monday" || day == "Tuesday"
|| day == "Wednesday" || day == "Thursday" || day == "Friday")
{
dayType = "Weekday";
}
else
{
dayType = "Something Wrong !!!";
}
}
}
static void DayComparisonMultiORSwitch()
{
string dayType = string.Empty;
string day = "Friday";//"Saturday";
for (int i = 0; i < SampleSize; i++)
{
switch (day)
{
case "Sunday":
case "Saturday":
dayType = "Weekend";
break;
case "Monday":
case "Tuesday":
case "Wednesday":
case "Thursday":
case "Friday":
dayType = "Weekday";
break;
default:
dayType = "Soething wrong !!";
break;
}
}
}
Performance
In this way and we can see the data and here again if-else if is clear winner. When first condition meets true then switch case takes approx 12 times more than If-else if. On the other hand, if Last condition is true then also If- else if has a gain of 1.5 time faster processing.
First True | Last True | ||||
If | Switch | Diff | if | switch | Diff |
770 | 9209 | 11.96 | 5775 | 8190 | 1.42 |
1529 | 18358 | 12.01 | 11296 | 16119 | 1.43 |
2296 | 27437 | 11.95 | 16823 | 23689 | 1.41 |
2995 | 36665 | 12.24 | 22364 | 31817 | 1.43 |
Comparison with int or other numeric data type?
Since it is about the behavior of conditional statement not about the comparison about data type, So for any data type this will behave the same and I have
static void DecideValueIfFirst()
{
int day = 1;
string dayType = string.Empty;
for (int i = 0; i < SampleSize; i++)
{
if (day == 1)
{
dayType = "Weekend";
}
else if (day == 3)
{
dayType = "Weekend";
}
else if (day == 4)
{
dayType = "Weekday";
}
else if (day == 5)
{
dayType = "Weekday";
}
else if (day == 6)
{
dayType = "Weekday";
}
else if (day == 7)
{
dayType = "Weekday";
}
else if (day == 8)
{
dayType = "Weekday";
}
else
{
dayType = "Something Wrong !!!";
}
}
}
static void DecideValueIfLast()
{
int day = 1;
string dayType = string.Empty;
for (int i = 0; i < SampleSize; i++)
{
if (day == 2)
{
dayType = "Weekend";
}
else if (day == 3)
{
dayType = "Weekday";
}
else if (day == 4)
{
dayType = "Weekday";
}
else if (day == 5)
{
dayType = "Weekday";
}
else if (day == 6)
{
dayType = "Weekday";
}
else if (day == 7)
{
dayType = "Weekday";
}
else if (day == 1)
{
dayType = "Weekend";
}
else
{
dayType = "Something Wrong !!!";
}
}
}
Performance
As we can see from the following observation, we still get the same performance difference –
first (A) | last (B) | Diff (B/A) |
413 | 1192 | 2.886199 |
817 | 2341 | 2.865361 |
1227 | 3492 | 2.845966 |
1641 | 4623 | 2.817185 |
2083 | 5761 | 2.765723 |
2491 | 6889 | 2.765556 |
2894 | 8019 | 2.770905 |
Disclaimer
For this analysis, I have used extreme case scenario as in first and last, to show the significant difference in performance and comparison. Your real life scenario may differ but I hope that this article gives you better understanding of how and what to use from conditional statements in C#.
Share your feedback and download the code to experiment further.