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();
- p.GetPerformanceIfcondition();
- p.GetPerformanceSwitchCondition();
Exploring the if with else
- p.GetPerformanceIfcondition();
Set the method start time.
- string startingTime = DateTime.Now.ToLongTimeString(); // When this method call starting time assign the value of starting time.
Loop to check the performance. This loop continues looping until the i exceeds this
10000000 value.
- for (int i = 0; i < 10000000; i++)
- {
-
- }
Get a random number for the if statement. Random is a predefined class, in the class is the next function, this function returns the one single value. Random one single value. rnd.Next('seed value','max value). This function returns the value every time between 1 and 12.
- Random rnd = new Random();
- int month = rnd.Next(1, 13);
If statement in a loop.
- if (month == 1)
- {
- }
- else
- if (month == 2)
- {
-
- }
- else
- if (month == 3)
- {
- }
-
The complete method is placed here.
- 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);
- 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);
-
-
- }
Switch Statement
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:
The output of both functions are run in a console based application.
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.