5 tips to improve performance of C# code: Part 4

Welcome to the C# Performance Enhancement tutorial series. I have been writing about on this in my previous articles of this series. If you are interested enough in learning about performance enhancement in C# then please go through all of the following.
OK, let's start article 4 of this performance improvement series of articles. Here I will show a few ADO.NET tips too. I have tested my code in my computer and as performance varies from system configuration to configuration you may encounter different results if you run this code in your computer. But I hope it will not show reciprocal results, it may show slide differently.
 
Step 1: Check the Connection Pooling of your project
 
If you don't any concept of connection pooling then I suggest you go through the following few lines.
 
A connection object is one of the most resource consuming objects in ADO.NET. So we need to manage this object very carefully. Now, opening a new connection and closing it takes a lot of resources. So, rather than creating a connection object again and again, what if we keep a connection object frozen (yes like vegetables) to reuse them later. In the following example I have shown the performance difference between both approaches. In the ConnectionWithPool() function I have used Pooling in the connection string but in ConnectWithoutPool() I did not.
 
Connection Pooling 
  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Diagnostics;  
  4. using System.IO;  
  5. using System.Data.SqlClient;   
  6. namespace Test1  
  7. {  
  8.     class TestConnection  
  9.     {  
  10.         public static void ConnectionWithPool()  
  11.         {  
  12.             SqlConnection con = new SqlConnection();  
  13.             con.ConnectionString = "Data Source=.\\SQL_INSTANCE2;Initial Catalog=dbPOSPRO;Integrated Security=True;Pooling=True";  
  14.             for (int i = 0; i < 100; i++)  
  15.             {  
  16.                 con.Open();  
  17.                 con.Close();  
  18.             }   
  19.         }  
  20.         public static void ConnectWithoutPool()  
  21.         {  
  22.             SqlConnection con = new SqlConnection();  
  23.             con.ConnectionString = "Data Source=.\\SQL_INSTANCE2;Initial Catalog=dbPOSPRO;Integrated Security=True;Pooling=False";  
  24.             for (int i = 0; i < 100; i++)  
  25.             {  
  26.                 con.Open();  
  27.                 con.Close();  
  28.             }   
  29.         }  
  30.     }   
  31.     class Program  
  32.     {  
  33.         static void Main(string[] args)  
  34.         {  
  35.             Stopwatch sw = new Stopwatch();  
  36.             sw.Start();  
  37.             TestConnection.ConnectionWithPool();  
  38.             sw.Stop();  
  39.             Console.WriteLine("With Pooling: "+sw.ElapsedTicks);   
  40.             sw.Restart();  
  41.             TestConnection.ConnectWithoutPool();  
  42.             sw.Stop();  
  43.             Console.WriteLine("Without Pooling: " + sw.ElapsedTicks);   
  44.             Console.ReadLine();  
  45.         }  
  46.     }  
  47. }  
 
Yes, the output is saying that if we use the Pooling option then the performance will be improved three times.
 
So ,the single line conclusion is "Always use connection pooling to enhance ADO.NET code performance".
 
Step 2: Implement a "Using" block to manage resources properly
 
Nothing new in here, if you are inexperienced then you have probably heard or read this advice a thousand times. I will also give the same advice in this point but with evidence (read the practical example).
 
Within the withUsing() function I have implemented a Using block to manage the connection object properly but in the WithuOutUsing() function I did not. Please go through the following code to understand and keep enough courage to see the output screen (Ha ..Ha..).
  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Diagnostics;  
  4. using System.IO;  
  5. using System.Data.SqlClient;   
  6. namespace Test1  
  7. {  
  8.     class TestConnection  
  9.     {  
  10.         public static void WithuUsing()  
  11.         {  
  12.             for (int i = 0; i < 10; i++)  
  13.             {  
  14.                 using (SqlConnection con = new SqlConnection("Data Source=.\\SQL_INSTANCE2;Initial Catalog=dbPOSPRO;Integrated Security=True;Pooling=false"))  
  15.                 {  
  16.                      con.Close();  
  17.                 }  
  18.             }   
  19.         }  
  20.         public static void WithuOutUsing()  
  21.         {  
  22.             SqlConnection con = null;  
  23.             for (int i = 0; i < 10; i++)  
  24.             {  
  25.                 con = new SqlConnection("Data Source=.\\SQL_INSTANCE2;Initial Catalog=dbPOSPRO;Integrated Security=True;Pooling=false");  
  26.                 con.Open();  
  27.                 con.Close();                
  28.             }   
  29.         }  
  30.     }   
  31.     class Program  
  32.     {  
  33.         static void Main(string[] args)  
  34.         {  
  35.             Stopwatch sw = new Stopwatch();  
  36.             sw.Start();  
  37.             TestConnection.WithuUsing();  
  38.             sw.Stop();  
  39.             Console.WriteLine("With Using:   "+sw.ElapsedTicks);  
  40.             sw.Restart();  
  41.             TestConnection.WithuOutUsing();  
  42.             sw.Stop();  
  43.             Console.WriteLine("Without Using: " + sw.ElapsedTicks);   
  44.             Console.ReadLine();  
  45.         }  
  46.     }  
  47. }  
 
Yes, if you manage a resource properly in your program with a Using block then it might enhance performance up to 78 times.
 
Again, the single line conclusion is "Use using to manage resources and improve performance".
 
Step 3: Use local variables in high label of iteration
 
In a project, looping and heavy iteration is a common scenario. Generally we use for, while or do while loop (yes a foreach loop is internally converted to a for loop) in our code and we initialize the loop counter variable (I, j generally, I also don't know why geek choose I or j rather than the use of the remaining characters. (Ha.. Ha..) It might be similar like class C IP address 192.168 .*.* , No one knows why but people use it.) to go through all iterations.
 
OK, we are getting off-topic, let's return to the subject. Always make a loop counter variable or other variable local when you are performing some operation within a certain function. I have written the following code to show it practically. Please go through the following code.
  1. class test  
  2. {  
  3.      public void loop1()  
  4.      {  
  5.          int j = 0;  
  6.          for (int i = 0; i < 250000; i++)  
  7.          {  
  8.               j = j + 1;  
  9.          }  
  10.     }  
  11.     int i;  
  12.     int j = 0;  
  13.     public void loop2()  
  14.     {          
  15.          for (i = 0; i < 250000; i++)  
  16.          {  
  17.               j = j + 1;  
  18.          }  
  19.     }  
  20. }   
  21. class Program  
  22. {           
  23.      static void Main(string[] args)  
  24.      {  
  25.           test t = new test();   
  26.           Stopwatch sw = new Stopwatch();  
  27.           sw.Start();            
  28.           t.loop1();  
  29.           sw.Stop();  
  30.           Console.WriteLine("With Loop1:   " + sw.ElapsedTicks);   
  31.           sw.Restart();  
  32.           t.loop2();             
  33.           sw.Stop();  
  34.           Console.WriteLine("With Loop2:   " + sw.ElapsedTicks);  
  35.           Console.ReadLine();  
  36.     }  
  37. }  
Here is the output screen. We can see that when we define a variable as local (within the function) the performance improves.
 
 
Step 4: LINQ is much slower than other searching techniques
 
Hold your breath, I will show that soon. First of all this point is not against to LINQ , I know it is a very useful feature of C# and we can apply the same LINQ query to various data sources. Bla bla.. But think twice before using LINQ in your next code.
 
I have implemented one searching scenario to show a demonstration. I have created an array of 1000 integer numbers and filled them sequentially from 0 to n. Then within a LINQ function I have implemented a LINQ query to search for a number (say for example 70 in my case) and in the second function I have implemented a simple sequential search to search for the same number. (Yes you read that correct;ly, a sequential search is the most time consuming searching algorithyam, and yes, a binary search is far better than a sequential search.)
  1. class test  
  2. {  
  3.      public void LINQ()  
  4.      {  
  5.          int []a = new int[100];             
  6.          for (int i = 0; i < a.Length; i++)  
  7.          {  
  8.               a[i] =i;  
  9.          }  
  10.          var v = from p in a where p == 70 select p;   
  11.      }         
  12.      public void Linear()  
  13.      {  
  14.           int[] a = new int[1000];             
  15.           for (int i = 0; i < a.Length; i++)  
  16.           {  
  17.               a[i] = i;  
  18.           }   
  19.           for (int i = 0; i < a.Length; i++)  
  20.           {  
  21.               if (a[i] == 70)  
  22.               {  
  23.                   int b = a[i];  
  24.                   break;  
  25.               }  
  26.           }  
  27.      }   
  28. }   
  29. class Program  
  30. {           
  31.      static void Main(string[] args)  
  32.      {  
  33.           test t = new test();  
  34.           Stopwatch sw = new Stopwatch();  
  35.           sw.Start();  
  36.           t.LINQ();             
  37.           sw.Stop();  
  38.           Console.WriteLine("With LINQ:   " + sw.ElapsedTicks);    
  39.           sw.Restart();  
  40.           t.Linear();             
  41.           sw.Stop();  
  42.           Console.WriteLine("With Search:   " + sw.ElapsedTicks);  
  43.           Console.ReadLine();  
  44.      }  
  45. }  
 
Our POC result shows the worst searching method is 17 times faster than LINQ. Now, why is LINQ is slower?
 
LINQ is developer friendly but not performance friendly. It's easy to read and write a LINQ query but internally the LINQ query is converted into a search function and in conversion it requires a lot of resources.
 
So, our conclusion ia "I do not recommend use of LINQ but use LINQ in the proper place. Simply to use LINQ, don't use LINQ."
 
Step 5: Use the files system to save an image rather than a database.
 
Let me explain this point from my real experience. A few days before we were trying to implement a project where file uploading was very important.
 
Now, there are two approaches to solve this:
  1. Keep it file in the file system
  2. Keep the file in a database (after converting it to binary format)
I have searched in various blogs, articles and discussion forums. Some suggest the filesystem, few are in favor of the database. I was getting confused, and then I implemented both approaches and my experience said
 
"Keeping the file in the file system is much faster than keeping it in the database after converting to binary.". Here, this article already became bulky and I don't want to bore you any more. In a future article I will try to show it.
 
Conclusion
 
If you are reading up to this line, I hope you have enjoyed this article. All types of suggestions are welcome.
 
Special line: Again, like other articles this line is dedicated to my dear Sam. Sam, "I have nominated you as my best reader. Waiting for your suggestion and valuable comments".


Similar Articles