5 Tips to Improve Your C# Code: Part 1

Before reading this article go through the following article:
 
 
Dear reader, in this article I provide a few best practices in C# programming. In my previous article I explained "How to improve performance of C# code", you can read it here.
 
Today's topic is very similar with that, if you really liked my first article then I can assure you that you will enjoy this too. So let's start enjoying.
 
Are you using exception handling mechanisms for user's input validation?
 
If yes, then you are the person who is reducing your project execution speed by 62 times. Do you not believe me? Wait a few minutes; I will show you how. But before that example let's learn where exception handling is really necessary.
 
For example you are validating user's data and for any invalid input you are raising an exception and throwing it to the client (I am assuming you are checking the user's input in business logic) as in the following:
  1. class BusinessLogcCheck  
  2. {  
  3.     public void Check()  
  4.     {  
  5.         try  
  6.         {  
  7.             //Your validation code is here  
  8.         }  
  9.         catch (Exception ex)  
  10.         {  
  11.             throw new Exception("My own exception");  
  12.         }  
  13.     }  
  14. }  
Dear friend, in the next example you will realize how bad the practice is if you see the output screen. Let's see the following code.
  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Text;  
  5. using System.Diagnostics;  
  6. using System.IO;  
  7. using System.Net;  
  8. using System.Net.NetworkInformation;  
  9. namespace Test1  
  10. {  
  11.     class Program  
  12.     {  
  13.         public static void ThrowTest()  
  14.         {  
  15.             throw new Exception("This is exceptopn");  
  16.         }  
  17.         public static Boolean Return()  
  18.         {  
  19.             return false;  
  20.         }  
  21.         static void Main(string[] args)  
  22.         {  
  23.             Stopwatch sw = new Stopwatch();  
  24.             sw.Start();  
  25.             try  
  26.             {  
  27.                     ThrowTest();  
  28.             }  
  29.             catch  
  30.             {  
  31.             }  
  32.             sw.Stop();  
  33.             Console.WriteLine("With Exception " + sw.ElapsedTicks);  
  34.             sw.Restart();  
  35.             try  
  36.             {  
  37.                 Return();  
  38.             }  
  39.             catch  
  40.             {  
  41.             }  
  42.             sw.Stop();  
  43.             Console.WriteLine("With Return " + sw.ElapsedTicks);  
  44.             Console.ReadLine();  
  45.         }  
  46.     }  
  47. }  
And this is the output for which you are waiting.
 
My proof of concept is very simple. In one function I am raising an exception and in another I am returning a Boolean value after checking the user input. And I have attached a screen of a calculator (Ha Ha..) to make you believe how exception handling impacts code performance.
 
So, we can draw the one conclusion "Don't raise an exception for user input validation . Use a Boolean return technique (or something like that) to validate input in Business logic". Because exception objects are very costly ones. (But less costlier than your favorite shirt.. Ha Ha.. )
 
Never implement try-Catch within loop
 
Yes, It also related to exception handling . I repeat "Never implement try-catch within loop". Let me prove that it with an example.
  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Text;  
  5. using System.Diagnostics;  
  6. using System.IO;  
  7. using System.Net;  
  8. using System.Net.NetworkInformation;  
  9. namespace Test1  
  10. {  
  11.     class Program  
  12.     {  
  13.         static void Method1()  
  14.         {  
  15.             for (int i = 0; i < 1000; i++)  
  16.             {  
  17.                 try  
  18.                 {  
  19.                     int value = i * 100;  
  20.                     if (value == -1)  
  21.                     {  
  22.                         throw new Exception();  
  23.                     }  
  24.                 }  
  25.                 catch  
  26.                 {  
  27.                 }  
  28.             }  
  29.         }  
  30.         static void Method2()  
  31.         {  
  32.             try  
  33.             {  
  34.                 for (int i = 0; i < 1000; i++)  
  35.                 {  
  36.                     int value = i * 100;  
  37.                     if (value == -1)  
  38.                     {  
  39.                         throw new Exception();  
  40.                     }  
  41.                 }  
  42.             }  
  43.             catch  
  44.             {  
  45.             }  
  46.         }  
  47.         static void Main(string[] args)  
  48.         {  
  49.             Stopwatch sw = new Stopwatch();  
  50.             sw.Start();  
  51.             Method1();  
  52.             sw.Stop();  
  53.             Console.WriteLine("Within Loop " + sw.ElapsedTicks);  
  54.             sw.Restart();  
  55.             Method2();  
  56.             sw.Stop();  
  57.             Console.WriteLine("Outside of Loop " + sw.ElapsedTicks);  
  58.             Console.ReadLine();  
  59.         }  
  60.     }  
  61. }  
And here is the output screen.
 
In this program in method1 I have implemented an exception handling mechanism within the for loop and in method2 I have implemented it without the loop. And our output window is saying that if we implement try-catch outside of the for loop then our program will execute 2 times faster than a try-catch inside the loop.
 
And again the single conclusion is "Don't implement a try-catch within a loop in your project. (Yes! Not only within a for loop but any loop.)".
 
Are you crazy enough to use the new operator to create an integer variable?
 
Dear reader, don't criticize me for this long title, and never use the new operator to create a simple integer variable. I know you will argue that if you use the new operator to create a simple integer variable then it will be automatically set to 0 and does not suffer from an error such as "Unassigned local variable" but is it really necessary to get an automatic assignment of 0 where your intention is to create a local variable to store something? Let's see how the new operator degrades performance of code execution.
  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Text;  
  5. using System.Diagnostics;  
  6. using System.IO;  
  7. using System.Net;  
  8. using System.Net.NetworkInformation;  
  9. namespace Test1  
  10. {  
  11.     class Program  
  12.     {  
  13.         static void Main(string[] args)  
  14.         {  
  15.             Stopwatch sw = new Stopwatch();  
  16.             sw.Start();  
  17.             for (int i = 0; i < 1000; i++)  
  18.             {  
  19.                 int a = new int();  
  20.                 a = 100;  
  21.             }  
  22.             sw.Stop();  
  23.             Console.WriteLine("Using New operator:- " + sw.ElapsedTicks);  
  24.             sw.Restart();  
  25.             for (int i = 0; i < 1000; i++)  
  26.             {  
  27.                 int a;  
  28.                 a = 100;  
  29.             }  
  30.             sw.Stop();  
  31.             Console.WriteLine("Without new operator:- "+ sw.ElapsedTicks);  
  32.             Console.ReadLine();  
  33.         }  
  34.     }  
  35. }  
A screenshot of the output is here:
 
Yes the new operator degrades execution speed 5 times. Hmm.. Sourav, I can deny the output screen but one thing!! You are creating 1000 variables at a time; in our project we won't create 1000 variables at a time, the maximum we will create is two or three.
 
Ok. Is your application a web application? If yes then please check the hit count of any popular web application and I am sure it's more than 1000 per day.
 
Again the single line conclusion "Don't be crazy enough to use the new operator to create an integer variable".
 
Choose best collection according to your purpose
 
We .NET developers are very much familiar with collections in C# and their use here and there to store values. Let's see how they perform for searching. See the performance of searching for an integer number. Here is my code.
  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Text;  
  5. using System.Diagnostics;  
  6. using System.IO;  
  7. using System.Net;  
  8. using System.Net.NetworkInformation;  
  9. namespace Test1  
  10. {  
  11.     class Program  
  12.     {  
  13.         static void Main(string[] args)  
  14.         {  
  15.             List<Int32> li = new List<Int32>(1000);  
  16.             Dictionary<intint> di = new Dictionary<intint>(1000);  
  17.             int[] arr = new int[1000];  
  18.             int a;  
  19.             for (int i = 0; i < 1000; i++)  
  20.             {  
  21.                 li.Add(i);  
  22.                 di.Add(i, i);  
  23.                 arr[i] = i;  
  24.             }  
  25.             Stopwatch sw = new Stopwatch();  
  26.             sw.Start();  
  27.             a = li[500];  
  28.             sw.Stop();  
  29.             Console.WriteLine("From list:- " + sw.ElapsedTicks);  
  30.             sw.Start();  
  31.             a = arr[500];  
  32.             sw.Stop();  
  33.             Console.WriteLine("From Integer array:- " + sw.ElapsedTicks);  
  34.             sw.Restart();  
  35.             a = di[500];  
  36.             sw.Stop();  
  37.             Console.WriteLine("From Dictionary:- " + sw.ElapsedTicks);  
  38.             Console.ReadLine();  
  39.         }  
  40.     }  
  41. }  
And the output is here.
 
Clearly we can see in the case of a dictionary collection the performance of a search is the worst and in the list and integer array the performance is very similar.
 
Function is good , but not all time
 
If you remember you're first few days of learning programing, you learned the one concept of always implementing a function to implement good practices in code and yes really it's good to implement a function to perform certain tasks. There are thousands of advantages of functions in programming but let's see how a function degrades performance of execution. Again I am saying, this point is not against functions but to show you simply how function calling is a costly mechanism and provides an idea of where to implement a function and where not to. Let's see the following code.
  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Text;  
  5. using System.Diagnostics;  
  6. using System.IO;  
  7. using System.Net;  
  8. using System.Net.NetworkInformation;  
  9. namespace Test1  
  10. {  
  11.     class test  
  12.     {  
  13.         public static void Print()  
  14.         {  
  15.             Console.WriteLine("I am function from Class");  
  16.         }  
  17.     }  
  18.     class Program  
  19.     {  
  20.         static void Main(string[] args)  
  21.         {  
  22.             Stopwatch sw = new Stopwatch();  
  23.             sw.Start();  
  24.             test.Print();  
  25.             sw.Stop();  
  26.             Console.WriteLine(sw.ElapsedTicks);  
  27.             sw.Restart();  
  28.             Console.WriteLine("I am single statement within main");  
  29.             sw.Stop();  
  30.             Console.WriteLine(sw.ElapsedTicks);  
  31.             Console.ReadLine();  
  32.         }  
  33.     }  
  34. }  
And the output screen:
 
 
Here I want to print a single message in the output window and at first I have implemented it within a static function and call it by class name and the second time I have just written it within the main function. Yes very simply by Console.Writeline(). And the output screen is saying that the single line execution is 9 times faster than the function. And obviously we will not start the debate of the topic "Advantages and disadvantages of functions" ( Ha Ha..).
 
So the single conclusion is "Try to understand the situation and make the best decision before blindly implementing a function"
 
Conclusion
 
Thanks for toleratng me for such a long time. I have done the test above in my laptop with a core i3 processor, 4GB of internal memory and Windows environment and taken the output in release mode after a stable condition of the program. If you use a different platform and different output then please look at the following. There is enough space to a write comment in the comment section.


Similar Articles