5 Tips to improve performance of C# code
In this article I show you 5 best practices of C# programming. I have learned these practices from my daily programming experience. I have tested all code in release mode and have taken screen shots after the stability of the development environment. And I think you will enjoy these tips.
Choose your data type before using it
For many types we prefer to not decide what data type to use in our daily programming life. Even a few months ago I too was among them. But when I started to learn best practices in programming to improve code performance I learned how a wrong data type can impact code. I will show one demonstration to prove this concept.
- staticvoid 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();
- }
In the code above at first I used a generic List to store 1000 integer values and in the second time for the same operation I used an integer array. And my output screenshot shows which storage mechanism is best for the integer array. Now, you may think why does the List take more time? The reason is that the List stores the data in object format and when we try to store the value type at first it converts it to a reference type, then it's stored. So the first point is to always choose the proper storage mechanism to get the best performance.
Use For loop instead of foreach
I am will now explain a very interesting fact. I think all of you are familiar with both for and foreach loops. Now if I ask you which one is faster ? Hmm... Don't know. Right?
Guys, a for loop is much faster than a foreach loop. Let's see 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();
And don't worry, I have tested this example in release mode and this screen shot is taken after several test runs. And still if you want to use a for loop then I will request you to have a look at the output screen shot one more time.
Choose when to use a class and when to use a structure
By accepting that you pretty much understand structures and classes in C# or at least in your favorite programming language, if they are present there. Ok, if you are thinking that "long ago I had learned structures and in daily coding life never used then" then you are among those 95% of developers who have never measured the performance of classes and structures. Don't worry; neither have I before writing this article.
And what about classes? Yes now and then we implement a class in our daily routine project development.
Now my question is "Which one is faster, class or structure"? I expect that you are thinking that "Never tested it". Ok then let's test it here. Have a look at the following code.
- 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();
- }
- }
- }
And the output is here:
Now it's clear that the structure is much faster than the class. Again, I have tested this code in release mode and taken at least 20 outputs to get the program to a stable position.
Now the big question is "why is a structure faster than a class"?
As we know, structure variables are value types and in one location the value (or structure variable) is stored.
And a class object is a reference type. In case of an object type the reference is created and the value is stored in some other location of memory. Basically the value is stored in a manageable heap and the pointer is created in the stack. And to implement an object in memory in this fashion, generally it will take more time than a structure variable.
Always use Stringbuilder for String concatenation operations
This point is very crucial for developers. Please use StringBuilder in place of String when you are making heavy string concatenation operations. To demonstrate how it impacts on code performance I have prepared the following example code. I am doing a string concatenation operation 500 times within the for loop.
- public classTest
- {
- public staticstring Name { get;set; }
- public staticString 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();
- }
- }
And this is the output.
Choose best way to assign class data member
Before assigning a value to your class variable, I suggest you look at the following code and output screen at this point.
- namespace Test
- {
- public classTest
- {
- 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();
- }
- }
- }
Yes, our output screen is saying that the data member is assigned using a property is much slower than direct assignment.