Hello friends, in my previous post, Writing Optimized Code – Part 1, we discussed how eliminating the piece of code to perform the task which is understood increased performance.
Today, I am going to discuss that how changing the order of the conditions will give some performance improvements. Yes, there are many places where you can apply this technique to get some performance gain.
Let’s take an example of determining whether out of two given numbers is larger, smaller, or equal. The very simple logic to determine requires if-else ladder in the following form:
If ( Number1 == Number2 )
Both Numbers are EQAL
Else If ( Number1 > Number2 )
Number 1 is Greater than Number 2
Else
Number 1 is Smaller than Number 2
Well, the above logic does not have any errors and will work very well. However, the chances of two numbers being equal are less than they are not equal. This will make the first If conditions evaluating false most of the time.
To get more real insights into what I am saying here, let’s have a look into the piece of code that has two methods with different if-else-if structure. I am calling the one which compares equality first as UnOptimized and the other as Optimized methods.
You can create a Console Application project and replace the Program.cs code with the below code.
using System; using System.Diagnostics; namespace WritingOptimizedCodePart2 { class Program { //Let's Create an integer array to hold 1000 numbers static int[] arr = new int[500000]; static void Main(string[] args) { Console.WriteLine("Initializing"); Initialize(); Console.WriteLine("Initializing Done - Calling Unoptimized Method"); DisplayPatternUnOptimized(); Console.WriteLine("Press the Enter key to call Optimized Method"); Console.ReadLine(); DisplayPatternOptimized(); Console.WriteLine("Press the Enter key to exit."); Console.ReadLine(); } static void Initialize() { //Create Random Number Object Random randomValue = new Random(); //Populate the array with random numbers between 1 to 100 for (int i = 0; i < arr.Length; i++) { arr[i] = randomValue.Next(1, 100); } } //UnOptimized Method Checking Equality First static void DisplayPatternUnOptimized() { int equal = 0; int nonEqual = 0; Stopwatch sw = new Stopwatch(); sw.Start(); for (int i = 0; i < arr.Length-1; i++) { if (arr[i]==arr[i+1]) { equal++; //Commenting it as it will increase execution time //You are free to uncomment if you have time //Console.WriteLine($"Comparing {arr[i] } and { arr[i+1] } :- both are equal."); } else if (arr[i] < arr[i + 1]) { nonEqual++; //Commenting it as it will increase execution time //You are free to uncomment if you have time //Console.WriteLine($"Comparing {arr[i] } and { arr[i + 1] } :- {arr[i] } is smaller than { arr[i + 1] }."); } else { nonEqual++; //Commenting it as it will increase execution time //You are free to uncomment if you have time //Console.WriteLine($"Comparing {arr[i] } and { arr[i + 1] } :- {arr[i] } is larger than { arr[i + 1] }."); } } sw.Stop(); Console.WriteLine($"Total Number of Equal matches {equal}.") ; Console.WriteLine($"Total Number of NON Equal matches {nonEqual}."); Console.WriteLine($"Unoptimized method took { sw.Elapsed.TotalMilliseconds } milliseconds."); } //Optimized Method static void DisplayPatternOptimized() { int equal = 0; //We do not require nonequal variable as it can be computed //Total - Equal = NonEqual Stopwatch sw = new Stopwatch(); sw.Start(); for (int i = 0; i < arr.Length - 1; i++) { int num1 = arr[i], num2 = arr[i + 1]; if (num1 < num2) { //Commenting it as it will increase execution time //You are free to uncomment if you have time //Console.WriteLine($"Comparing { num1 } and { num2 } :- { num1 } is smaller than { num2 }."); } else if (num1 > num2) { //Commenting it as it will increase execution time //You are free to uncomment if you have time //Console.WriteLine($"Comparing { num1 } and { num2 } :- { num1 } is larger than { num2 }."); } else { equal++; //Commenting it as it will increase execution time //You are free to uncomment if you have time //Console.WriteLine($"Comparing { num1 } and { num2 } :- both are equal."); } } sw.Stop(); Console.WriteLine($"Total Number of Equal matches {equal}."); Console.WriteLine($"Total Number of NON Equal matches {arr.Length-equal}."); Console.WriteLine($"Optimized method took { sw.Elapsed.TotalMilliseconds } milliseconds."); } } }
The below is the output in Debug version

Below is the 3 times execution of the program in Release mode.

As you can see in the screenshots, by re-ordering the conditions will give you performance gain (performance gain depends on the complexity and data).