The last article attempted to evaluate the performance of an if statement, you can check this link for more information about the if statement performance. In this article we will analyze what provides the best performance, the if statement or the switch statement. I have prefered the if statement.
I have created one Console Application for testing the if statements and switch statements.
- Program p = new Program(); // Class Object create
- p.GetPerformanceIfcondition(); // Call if else condition
- p.GetPerformanceSwitchCondition(); //Call switch case Condition
- p.GetPerformanceIfcondition(); // Call if else condition
Set the method start time.
- string startingTime = DateTime.Now.ToLongTimeString(); // When this method call starting time assign the value of starting time.
- for (int i = 0; i < 10000000; i++)
- {
- }
- Random rnd = new Random();
- int month = rnd.Next(1, 13); // creates a number between 1 and 12
- if (month == 1)
- {
- }
- else
- if (month == 2)
- {
- }
- else
- if (month == 3)
- {
- }
-
- public void GetPerformanceIfcondition()
- {
- Console.WriteLine("If else performance check");
- string endtime = DateTime.Now.ToShortTimeString();
- string startingTime = DateTime.Now.ToLongTimeString();
- Random rnd = new Random();
- for (int i = 0; i < 10000000; i++)
- {
-
- int month = rnd.Next(1, 13); // creates a number between 1 and 12
- if (month == 1)
- {
- }
- else
- if (month == 2)
- {
- }
- else
- if (month == 3)
- {
- }
- else
- if (month == 4)
- {
- }
- else
- if (month == 5)
- {
- }
- else
- if (month == 6)
- {
- }
- else
- if (month == 7)
- {
- }
- else
- if (month == 8)
- {
- }
- else
- if (month == 9)
- {
- }
- else
- if (month == 10)
- {
- }
- else
- if (month == 11)
- {
- }
- if (month == 12)
- {
- }
- }
- endtime = DateTime.Now.ToLongTimeString();
- TimeSpan t2 = DateTime.Parse(endtime).Subtract(DateTime.Parse(startingTime));
- Console.WriteLine(t2);
- }
We have already defined the preceding. We can also comare the performance between an if statement and a switch statement.
- public void GetPerformanceSwitchCondition()
- {
-
- }
The following is a for loop of the same as in the if statement.
- for (int i = 0; i < 10000000; i++)
- {
- }
In this function have used the switch statement.
- switch (month)
- {
- case 1:
- break;
- case 2:
- break;
- case 3:
- break;
- // Case 1: to Case 12:
Conclusion
From this article we hope to understand what provides the best performance. You can check it yourself. I have attached one console application. For any query provide you comments. Every comment is welcome.
Note: Live Demo: .NET Fiddle.

Onlymorons onthiswebsitePosted Feb 1, 2015, 5:34 PM
Your results are incorrect and your test setup is bad. This article should be removed