Performance Consideration for C# Conditional Statements

Atul Sharma

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.

See also  C# Collections - Behind the Scene: A Must for Every C# Programmers
When true condition is in the First
(A)
When true condition is in the Last
(B)
Performance
(B/A)
531554251.020696
10398106961.028659
15622159241.019332
20843211441.014441
26015263071.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. First case true performs approx 6 times faster than last case true in if- else if condition.

When true in First (A)When true in Last (B)Performance (B/A)
94253645.6942675
1768104895.9326923
2481156706.3160016
3159207656.5732827
3825258866.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.

See also  All About IEnumerable and IQueryable
First case is true (A)Last case is true (B)Diff (B/A)
91429137.9994531
1794517833.9937587
26599269571.013459
35236357111.013481
43943443271.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.

See also  Dynamics 365 : Many to Many (N:N) Relationship
First TrueLast True
IfSwitchDiff ifswitchDiff
770920911.96577581901.42
15291835812.0111296161191.43
22962743711.9516823236891.41
29953666512.2422364318171.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 following data to prove it. I changed the code

  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)
41311922.886199
81723412.865361
122734922.845966
164146232.817185
208357612.765723
249168892.765556
289480192.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.