5 Tips to Improve Your C# Code: Part 1

Before reading this article go through the following article:

  1. 5 Tips to Improve Performance of C# Code

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.

1. 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:

class BusinessLogcCheck

{

    public void Check()

    {

        try

        {

            //Your validation code is here

           

        }

        catch (Exception ex)

        {

            throw new Exception("My own exception");

        }

 

    }

}

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.
 

using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

using System.Diagnostics;

using System.IO;

using System.Net;

using System.Net.NetworkInformation;

namespace Test1

{

    class Program

    {

        public static void ThrowTest()

        {

            throw new Exception("This is exceptopn");

        }

        public static Boolean Return()

        {

            return false;

        }

 

        static void Main(string[] args)

        {

 

            Stopwatch sw = new Stopwatch();

            sw.Start();

 

            try

            {

                    ThrowTest();

            }

            catch

            {

               

            }

            sw.Stop();

            Console.WriteLine("With Exception " + sw.ElapsedTicks);

 

            sw.Restart();

            try

            {

                Return();

            }

            catch

            {

 

            }

            sw.Stop();

            Console.WriteLine("With Return " + sw.ElapsedTicks);

            Console.ReadLine();

        }

    }

}


And this is the output for which you are waiting.

Image1.jpg

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.. )

2. 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.
 

using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

using System.Diagnostics;

using System.IO;

using System.Net;

using System.Net.NetworkInformation;

namespace Test1

{

    class Program

    {

        static void Method1()

        {

            for (int i = 0; i < 1000; i++)

            {

                try

                {

                    int value = i * 100;

                    if (value == -1)

                    {

                        throw new Exception();

                    }

                }

                catch

                {

                }

            }

        }

        static void Method2()

        {

            try

            {

                for (int i = 0; i < 1000; i++)

                {

                    int value = i * 100;

                    if (value == -1)

                    {

                        throw new Exception();

                    }

                }

            }

            catch

            {

            }

        }

 

        static void Main(string[] args)

        {

 

            Stopwatch sw = new Stopwatch();

            sw.Start();

            Method1();

            sw.Stop();

 

            Console.WriteLine("Within Loop " + sw.ElapsedTicks);

 

            sw.Restart();

            Method2();

            sw.Stop();

            Console.WriteLine("Outside of Loop " + sw.ElapsedTicks);

            Console.ReadLine();

        }

    }

}


And here is the output screen.

Image2.jpg

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.)".

3. 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.
 

using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

using System.Diagnostics;

using System.IO;

using System.Net;

using System.Net.NetworkInformation;

namespace Test1

{

    class Program

    {

        static void Main(string[] args)

        {

            Stopwatch sw = new Stopwatch();

            sw.Start();

            for (int i = 0; i < 1000; i++)

            {

                int a = new int();

                a = 100;

            }

            sw.Stop();

            Console.WriteLine("Using New operator:- " + sw.ElapsedTicks);

            sw.Restart();

            for (int i = 0; i < 1000; i++)

            {

                int a;

                a = 100;

            }

            sw.Stop();

            Console.WriteLine("Without new operator:- "+ sw.ElapsedTicks);

            Console.ReadLine();

        }

    }

}


A screenshot of the output is here:
Image3.jpg

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".

4. 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.
 

using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

using System.Diagnostics;

using System.IO;

using System.Net;

using System.Net.NetworkInformation;

namespace Test1

{

    class Program

    {

        static void Main(string[] args)

        {

            List<Int32> li = new List<Int32>(1000);

            Dictionary<int, int> di = new Dictionary<int, int>(1000);

            int[] arr = new int[1000];

            int a;

           

            for (int i = 0; i < 1000; i++)

            {

                li.Add(i);

                di.Add(i, i);

                arr[i] = i;

            }

 

            Stopwatch sw = new Stopwatch();

            sw.Start();

            a = li[500];

            sw.Stop();

            Console.WriteLine("From list:- " + sw.ElapsedTicks);

 

 

            sw.Start();

            a = arr[500];

            sw.Stop();

            Console.WriteLine("From Integer array:- " + sw.ElapsedTicks);

 

 

            sw.Restart();

            a = di[500];

            sw.Stop();

            Console.WriteLine("From Dictionary:- " + sw.ElapsedTicks);

            Console.ReadLine();

        }

    }

}

And the output is here.

Image4.jpg

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.

Image5.jpg

5. 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.
 

using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

using System.Diagnostics;

using System.IO;

using System.Net;

using System.Net.NetworkInformation;

namespace Test1

{

    class test

    {

        public static void Print()

        {

            Console.WriteLine("I am function from Class");

        }

    }

 

 

    class Program

    {

        static void Main(string[] args)

        {

            Stopwatch sw = new Stopwatch();

            sw.Start();

            test.Print();

            sw.Stop();

            Console.WriteLine(sw.ElapsedTicks);

 

            sw.Restart();

            Console.WriteLine("I am single statement within main");

            sw.Stop();

            Console.WriteLine(sw.ElapsedTicks);

 

            Console.ReadLine();

        }

    }

}


And the output screen:

Image6.jpg

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.

Up Next
    Ebook Download
    View all
    Learn
    View all