Five tips to improve your C code (1)

Time:2021-6-14

Dear readers, in this article, I have provided some best practices of C # programming.

Do you use exception handling in user input validation?

If so, you are the one who has reduced your project execution speed by 62 times. Don’t you believe me? Wait a few minutes; I’ll show you how to do it. But before we start with this example, let’s see where exception handling is required.

For example, you are validating the user’s data. For any invalid input, you will throw an exception to the client, as follows:

Five tips to improve your C code (1); ” Copy code “)

Five tips to improve your C code (1)

class BusinessLogcCheck
{

public void Check()  
{  
    try  
    {  
        //Your validation code is here  
    }  
    catch (Exception ex)  
    {  
        throw new Exception("My own exception");  
    }  
}  

}

Five tips to improve your C code (1)

Five tips to improve your C code (1); ” Copy code “)

Dear friends, in the next example, if you see the output screen, you will realize how bad this is. Let’s take a look at the code below.

Five tips to improve your C code (1); ” Copy code “)

Five tips to improve your C code (1)

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();  
    }  
}  

}

Five tips to improve your C code (1)

Five tips to improve your C code (1); ” Copy code “)

This is the output you’re waiting for.

Five tips to improve your C code (1)

My proof of concept is very simple. In one function, I throw an exception, and in another, I return a Boolean value after checking user input. I also attached a calculator screen (ha ha…) to let you believe how exception handling affects code performance.

Therefore, we can conclude that “do not throw an exception for user input validation.” Use Boolean return technology (or similar technology) to verify input in business logic. Because the overhead of exception objects is very large.

Never try catch in a loop

Yes, it’s also about exception handling. I repeat, “never try catch in a loop.”. Let me give you an example.

Five tips to improve your C code (1); ” Copy code “)

Five tips to improve your C code (1)

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();  
    }  
}  

}

Five tips to improve your C code (1)

Five tips to improve your C code (1); ” Copy code “)

This is the output screen.

Five tips to improve your C code (1)

In the program of method 1, I implemented exception handling mechanism in the for loop, while in method 2, I implemented exception handling mechanism without loop. Our output window shows that if we implement try catch outside the for loop, the program will execute twice as fast as try catch inside the loop.

Again, the only conclusion is “don’t try catch in the loop of the project( yes! Not only in the for loop, but also in any loop.)

Are you crazy enough to use the new operator to create an integer variable?

Dear readers, don’t criticize me for writing such a long title, and don’t use the new operator to create a simple integer variable. I know you will say that if you use the new operator to create a simple integer variable, it will be automatically set to 0 without suffering from errors, such as “unassigned local variable”. But this really needs to get an automatic assignment to 0. Is your purpose to create a local variable to store it? Let’s see how the new operator reduces the performance of code execution.

Five tips to improve your C code (1); ” Copy code “)

Five tips to improve your C code (1)

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();  
    }  
}  

}

Five tips to improve your C code (1)

Five tips to improve your C code (1); ” Copy code “)

The output screenshot is as follows:

Five tips to improve your C code (1)

The new operator reduces the execution speed by five times. I can deny the output screen, but there’s one thing!! You create 1000 variables at a time; In our project, we don’t create 1000 variables at a time, up to two to three.

well. Is your application a web application? If so, please check the number of hits for any popular web application, I’m sure it’s more than 1000 per day.

Again, the line concludes, “don’t be crazy about using the new operator to create integer variables.”.

Choose the best set for your purpose

We. Net developers are very familiar with collections in C #, and the methods they use to store values. Let’s see how they perform searches. See the performance of search integers. This is my code.

Five tips to improve your C code (1); ” Copy code “)

Five tips to improve your C code (1)

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();  
    }  
}  

}

Five tips to improve your C code (1)

Five tips to improve your C code (1); ” Copy code “)

The output is here:

Five tips to improve your C code (1)

We can clearly see that in the case of dictionary, the performance of search is the worst, while in the case of list and integer array, the performance is very similar.

Five tips to improve your C code (1)

The method is good, but not all the time

If you remember the days when you first started learning programming, you learned the concept of always implementing a method to implement good exercises in code. Yes, it’s good to implement a method to perform certain tasks. Methods have thousands of advantages in programming, but let’s see how methods degrade execution performance. I emphasize again that this is not against methods, but simply shows that method invocation is an expensive mechanism and provides ideas on where to implement methods and where not to. Let’s take a look at the code below.

Five tips to improve your C code (1); ” Copy code “)

Five tips to improve your C code (1)

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();  
    }  
}  

}

Five tips to improve your C code (1)

Five tips to improve your C code (1); ” Copy code “)

Here is the screen output:

Five tips to improve your C code (1)

Here, I want to print a message in the output window. First, I implemented it in a static function and called it through the class name. Second, I just wrote it in the main function. Yes, it’s very simple to use console. Writeline(). The output screen shows that single line execution is 9 times faster than the function. So the only conclusion is “try to understand the situation and make the best decision before blindly performing a function.”

Recommended Today

VBS obtains the operating system and its version number

VBS obtains the operating system and its version number ? 1 2 3 4 5 6 7 8 9 10 11 12 ‘************************************** ‘*by r05e ‘* operating system and its version number ‘************************************** strComputer = “.” Set objWMIService = GetObject(“winmgmts:” _  & “{impersonationLevel=impersonate}!\\” & strComputer & “\root\cimv2”) Set colOperatingSystems = objWMIService.ExecQuery _  (“Select * from […]