5 Tips to Improve Performance of C# Code: Part 3

Welcome to the "C# Performance Improvement Article Series". This is my third presentation. So if you are new to this series of articles then I will recommend you try to go through the following code.
 
if(!study (First && Second && Third) ){
}else{
Welcome to "5 tips to improve performance of C# code -part 3";
}
 
Ha.. Ha.., No, this is not my first point or I am not going to measure performance of this funny pseudo code. And like every article I repeat a few lines. I have tested the following code in my Core i3 CPU, 4GB primary memory and Windows 7 platform. If you are in a different hardware configuration or using a different platform then your output may vary with my output screen and the output may vary depending on your current running process. As all points are performance testing I have tested them in release mode and taken a screen shot in a stable situation for all the code. Let's start with tip number 1.
 
How you check empty string in your code?
 
In this point I am going to show you three empty or null string checking styles. I hope you are familiar with all styles but may not familiar with their performance. Let's start with a small example. In the following there are three functions (Yes all static. I am lazy, and don't want to create the object again). In the first style I am using the Length property. In the second I am using a space or empty string (" "). And in the third case I am using an Empty property of the string class. The following is my test code.
  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Diagnostics;  
  4. using System.IO;  
  5. namespace Test1  
  6. {  
  7.     public class Compare  
  8.     {  
  9.         public static void First(string Value)  
  10.         {  
  11.             if (Value.Length != 0)  
  12.             {  
  13.             }  
  14.         }  
  15.         public static void Second(string Value)  
  16.         {  
  17.             if (Value != "")  
  18.             {  
  19.             }  
  20.         }  
  21.         public static void Third(string Value)  
  22.         {  
  23.             if (Value != string.Empty )  
  24.             {  
  25.             }  
  26.         }  
  27.     }  
  28.     class Program  
  29.     {  
  30.         static void Main(string[] args)  
  31.         {  
  32.             Stopwatch sw = new Stopwatch();  
  33.             sw.Start();  
  34.             Compare.First("Sourav");  
  35.             sw.Stop();  
  36.             Console.WriteLine("Using Length: "+sw.ElapsedTicks);  
  37.             sw.Restart();  
  38.             Compare.Second("Sourav");  
  39.             sw.Stop();  
  40.             Console.WriteLine("Using !=     " +sw.ElapsedTicks);  
  41.             sw.Restart();  
  42.             Compare.Third("Sourav");  
  43.             sw.Stop();  
  44.             Console.WriteLine("Using Empty: " + sw.ElapsedTicks);  
  45.             Console.ReadLine();  
  46.         }  
  47.     }  
  48. }  
And the output screen is:
 
 
We can see the Length measuring style (the first one) is taking the most time. And the String.Empty style is the least time consuming process.
 
So, the single line conclusion "Use of String.Empty to check whether the string is null or not".
 
Change your style of type casting
 
Yes, change it if you are not implementing the proper type casting technique. In the following I show two traditional styles of type casting and their performance impact on code. The first style (and the worst) is very simple, by using parenthesees () used by most of developers. And the second style is by the as keyword. In the following code I have implemented both of them. Let's go through the following code.
  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Diagnostics;  
  4. using System.IO;  
  5. namespace Test1  
  6. {  
  7.     public class Base  
  8.     {  
  9.     }  
  10.     public class Derive : Base  
  11.     {  
  12.     }  
  13.     class Program  
  14.     {  
  15.         static void Main(string[] args)  
  16.         {  
  17.             Derive d = new Derive();  
  18.             Stopwatch sw = new Stopwatch();  
  19.             sw.Start();  
  20.             Base b =(Base) d;  
  21.             sw.Stop();  
  22.             Console.WriteLine("Using type cust : "+ sw.ElapsedTicks);  
  23.             sw.Restart();  
  24.             Base c = d as Base;  
  25.             sw.Stop();  
  26.             Console.WriteLine("Using as keyword : "+ sw.ElapsedTicks);  
  27.             Console.ReadLine();  
  28.         }  
  29.     }  
  30. }  
And here is the output screen:
 
Hmm.. Our popular worst technique is 6 times slower than the as keyword. Now, in this point I will not write single line conclusion, it's your choice of how to cast objects.
 
Efficient string comparison method
 
Yes, one more tip regarding strings. We know there are two popular string comparison methods we frequently use. One is the "operator ==" and another one is using the Equals() method of the String class.
 
One day I asked one of my colleagues "Which one do you like the most?" He replied the first one (in other words operator ==). And I asked him why? He replied "It's very simple, easy and from my first of C# learning I have been using it and I am happy with it, I will not change my style". Hmm, if you are also in that situation then I suggest you have a look at the output screen first then in the code.
  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Diagnostics;  
  4. using System.IO;  
  5. namespace Test1  
  6. {  
  7.     public class Test  
  8.     {  
  9.         public static void First(String Value)  
  10.         {  
  11.             for (int i = 0; i < 100; i++)  
  12.             {  
  13.                 if (Value == "Sourav")  
  14.                 {  
  15.                     continue;  
  16.                 }  
  17.             }  
  18.         }  
  19.         public static void Second(String Value)  
  20.         {  
  21.             for (int i = 0; i < 100; i++)  
  22.             {  
  23.                 if (Value.Equals("Sourav"))  
  24.                 {  
  25.                     continue;  
  26.                 }  
  27.             }  
  28.         }  
  29.    }  
  30.     class Program  
  31.     {  
  32.         static void Main(string[] args)  
  33.         {  
  34.             Stopwatch sw = new Stopwatch();  
  35.             sw.Start();  
  36.             Test.First("Sourav");  
  37.             sw.Stop();  
  38.             Console.WriteLine("Using == : "+ sw.ElapsedTicks);  
  39.             sw.Restart();  
  40.             Test.Second("Sourav");  
  41.             sw.Stop();  
  42.             Console.WriteLine("Using Equals : "+ sw.ElapsedTicks);  
  43.             Console.ReadLine();  
  44.         }  
  45.     }  
  46. }  
 
You I have an attached calculator for quick calculation (Ha..Ha..). And the screen shows that the use of the "==" style is 190 times slower than the String comparison function (Equals()). Again I am not going to write single line conclusion. It's your responsibility to change your style and share the image above (output screen) to your friend in a lazy coffee break.
 
Impalement for loop with a little trick
 
Before starting I want to let you know something. It's not a very important point. Or it will be a very important trick to adapt. Here I will show how to implement our traditional for loop with a little spice. If you go through the following code then you will find in the second "for" implementation a local variable is using fewer times and that's why consumtion is less time but not very less. So, it's a best practice to use a variable less number of times.
  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Diagnostics;  
  4. using System.IO;  
  5. namespace Test1  
  6. {  
  7.     public class Base  
  8.     {  
  9.         public static void First(Int32 limit)  
  10.         {  
  11.             for (int i = 0; ++i <= limit; )  
  12.             {  
  13.             }  
  14.         }  
  15.         public static void Second(Int32 limit)  
  16.         {  
  17.             for (int i = limit; -- i >= 0; )  
  18.             {  
  19.             }  
  20.         }  
  21.     }  
  22.     class Program  
  23.     {  
  24.         static void Main(string[] args)  
  25.         {  
  26.             Stopwatch sw = new Stopwatch();  
  27.             sw.Start();  
  28.             Base.First(100);  
  29.             sw.Stop();  
  30.             Console.WriteLine("First "+ sw.ElapsedTicks);  
  31.             sw.Restart();  
  32.             Base.Second(100);  
  33.             sw.Stop();  
  34.             Console.WriteLine("Second : "+ sw.ElapsedTicks);  
  35.             Console.ReadLine();  
  36.         }  
  37.     }  
  38. }  
In the following my output window is:
 
Let's write the single line conclusion "Be smart both in time of writing loop iteration code. (And with a new girlfriend.This tip is only for junior male developers, those who are my age.)"
 
Inheritance is a good practice but not always
 
We know one beautiful feature of OOP is inheritance, and it reduces code redundancy, improves code maintenance and so on. I am not denying them but my fifth point is against unnecessarily creating small classes here and there. If it is really not needed then don't create a class hierarchy. Have a look at the following code.
  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Diagnostics;  
  4. using System.IO;  
  5. namespace Test1  
  6. {  
  7.     public class Base  
  8.     {  
  9.     }  
  10.     public class Derive  :Base  
  11.     {  
  12.         public string name;  
  13.     }  
  14.     public class Concrete  
  15.     {  
  16.         public string name;  
  17.     }  
  18.     class Program  
  19.     {  
  20.         static void Main(string[] args)  
  21.         {  
  22.             Stopwatch sw = new Stopwatch();  
  23.             sw.Start();  
  24.             Derive d = new Derive();  
  25.             d.name = "Sourav";  
  26.             sw.Stop();  
  27.             Console.WriteLine("Derive style : "+ sw.ElapsedTicks);  
  28.             sw.Restart();  
  29.             Concrete c = new Concrete();  
  30.             c.name = "Sourav";  
  31.             sw.Stop();  
  32.             Console.WriteLine("Concrete class : "+ sw.ElapsedTicks);  
  33.             Console.ReadLine();  
  34.         }  
  35.     }  
  36. }  
At first I created two small classes and between them I am not at all using the first one. It's serving as base class. In the second scenario I have created a single concrete class; there is no concept of inheritance on it. And within the main () method I am creating an object of both of them. Let's see the output screen.
 
 
As the output screen says, object creation in a concrete class is much faster than a derived class style. Let's conclude with the single line comment "Don't implement class hierarchy if not needed."
 
Conclusion
 
Dear reader, thanks for completing this article by wasting your valuable time. (Because most readers do not read top to button, if you read, it's my personal achievement). All types of comments are welcome. (Waiting for dear Sam's comment, -- Dear Sam, this line is only for you".


Recommended Free Ebook
Similar Articles