Five tips to improve your C code (2)

Time:2021-6-11

In this article, I’ll show you five best practices of C # programming. I learned these practices from my everyday programming experience. I tested all the code in release mode and took a screen capture after the development environment was stable. I think you’ll like the suggestions.

Select a data type before using it

For many types, we prefer not to decide what data type to use in our daily programming life. Just a few months ago, I was one of them. But when I started learning best practices in programming to improve code performance, I learned how wrong data types affect code. I’m going to show a demonstration to prove the concept.

static void Main(string[] args)  
{  
    List<Int32> li = new List<int>();  
    Stopwatch sw =new Stopwatch();  
    sw.Start();  
    for (int i = 0; i < 10000; i++)  
    {  
        li.Add(i);  
    }  
    sw.Stop();  
    Console.Write("Using Arraylist(Object)" + sw.ElapsedTicks + "n");  
    sw.Reset();  
    sw.Start();  
    Int32[] a = new Int32[10000];  
    for (int i = 0; i < 10000; i++)  
    {  
        a[i] = i;  
    }  
    sw.Stop();  
    Console.Write("Using Value(Integer Array)" + sw.ElapsedTicks);  
    Console.ReadLine();  
} 

Five tips to improve your C code (2)
In the above code, first I used a list to store 1000 integer values. The second time I performed the same operation, I used an integer array. My output screenshot shows which storage mechanism works best for integer arrays. Now, you may wonder why this list takes more time? The reason is that list stores data in object format, and when we first try to store a value type, it converts it to a reference type, and then stores it. Therefore, the first point is to always choose the appropriate storage mechanism for optimal performance.

Use for loop instead of foreach

Now I want to explain a very interesting fact. I think you’re all familiar with the for and foreach loops. Now if I ask you which is faster? Well, I don’t know. Right?

Guys, the for loop is much faster than the foreach loop. Let’s take a look at the following example.

List<Int32> Count = new List<int>();
List<Int32> lst1 = new List<Int32>();
List<Int32> lst2 = new List<Int32>();

for (int i = 0; i < 10000; i++)
{
    Count.Add(i);
}

Stopwatch sw = new Stopwatch();
sw.Start();
for (int i = 0; i < Count.Count; i++)
{
    lst1.Add(i);
}
sw.Stop();

Console.Write("For Loop :- " + sw.ElapsedTicks + "n");
sw.Restart();

foreach (int a in Count)
{
    lst2.Add(a);
}
sw.Stop();
Console.Write("Foreach Loop:- " + sw.ElapsedTicks);
Console.ReadLine();

Five tips to improve your C code (2)

Don’t worry, I’ve tested this example in release mode, and this screenshot was taken after several test runs.

Choose when to use classes and when to use structs

Accept the fact that you basically understand the structs and classes in C #, or at least understand the structs and classes (if they exist) in your favorite programming language. Well, if you’re thinking, “I learned about structs a long time ago, but I’ve never used them in my daily coding life,” then you’re one of the 95% of developers who’ve never measured the performance of classes and structs. don’t worry; Before writing this article, I didn’t either.

What about classes? Yes, from time to time, we implement a class in our daily project development.

Now my question is “which is faster, class or struct”? I guess you think, “never tested.”. OK, let’s test it. Look at the code below.

namespace BlogProject
{
    struct MyStructure
    {
        public string Name;
        public string Surname;
    }
    class MyClass
    {
        public string Name;
        public string Surname;
    }
    class Program
    {
        static void Main(string[] args)
        {

            MyStructure[] objStruct = new MyStructure[1000];
            MyClass[] objClass = new MyClass[1000];


            Stopwatch sw = new Stopwatch();
            sw.Start();
            for (int i = 0; i < 1000; i++)
            {
                objStruct[i] = newMyStructure();
                objStruct[i].Name = "Sourav";
                objStruct[i].Surname = "Kayal";
            }
            sw.Stop();
            Console.WriteLine("For Structure:- " + sw.ElapsedTicks);
            sw.Restart();

            for (int i = 0; i < 1000; i++)
            {
                objClass[i] = newMyClass();
                objClass[i].Name = "Sourav";
                objClass[i].Surname = "Kayal";
            }
            sw.Stop();
            Console.WriteLine("For Class:- " + sw.ElapsedTicks);

            Console.ReadLine();
        }
    }
}

The results are as follows

Five tips to improve your C code (2)
Now it’s clear that structs are much faster than classes. Similarly, I tested the code in release mode and got at least 20 outputs to keep the program in a stable position.

Now the biggest question is “Why are structs faster than classes?”

As we all know, struct variables are value types, and values (or struct variables) are stored in one location.

Class objects are reference types. If it is an object type, a reference is created and the value is stored elsewhere in memory. Basically, values are stored in a manageable heap and pointers are created in the stack. Implementing an object in memory in this way usually takes more time than structure variables.

Always use StringBuilder to connect strings

This is critical for developers. When performing a large number of string splicing operations, use StringBuilder instead of string. To demonstrate its impact on code performance, I’ve prepared the following sample code. I did 500 string stitching operations in the for loop.

public classTest
{
    public static string Name { get; set; }
    public static string surname;  
}  
class Program
{
    static void Main(string[] args)
    {
        string First = "A";
        StringBuilder sb = new StringBuilder("A");

        Stopwatch st = new Stopwatch();
        st.Start();
        for (int i = 0; i < 500; i++)
        {
            First = First + "A";
        }
        st.Stop();
        Console.WriteLine("Using String :-" + st.ElapsedTicks);
        st.Restart();

        for (int i = 0; i < 500; i++)
        {
            sb.Append("A");
        }
        st.Stop();
        Console.WriteLine("Using Stringbuilder :-" + st.ElapsedTicks);
        Console.ReadLine();
    }
}

  This is the output:
Five tips to improve your C code (2)

Choose the best way to assign class data members

Before assigning values to class variables, I recommend that you now look at the following code and output screens.

namespace Test
{  
    public class Test  
    {  
        public staticstring Name { get; set; }
        public staticString surname;
    }
    class Program
    {
        static void Main(string[] args)
        {

            Stopwatch st = new Stopwatch();
            st.Start();
            for (int i = 0; i < 100; i++)
            {
                Test.Name = "Value";
            }
            st.Stop();
            Console.WriteLine("Using Property: " + st.ElapsedTicks);
            st.Restart();
            for (int i = 0; i < 100; i++)
            {
                Test.surname = "Value";
            }
            st.Stop();
            Console.WriteLine("Direct Assign: " + st.ElapsedTicks);
            Console.ReadLine();
        }
    }  
} 

Five tips to improve your C code (2)

Yes, our output screen says that using attributes to assign data members is much slower than directly assigning them.

 Welcome to official account official account. If you love foreign technical articles, you can recommend it to me through public comments.
Five tips to improve your C code (2)