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

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




jubula samalPosted Nov 22, 2022, 6:57 AM
Nice article
Prashant ChoudharyPosted Feb 22, 2022, 5:36 AM
Your example is wrong in foreach, You are accessing the element from a list in second case however in the first one you are using a number directly.
Dinesh KumarPosted Dec 28, 2021, 4:27 AM
Nice article
Rainer KordmaaPosted Jul 17, 2020, 4:10 AM
Taking any of these recommendations as gospel is a good way to screw yourself over. As a rule of thumb you are not smarter than the compiler. If you think you might have found an edge case where the compiler is not doing what it's supposed to do and you can do better, you need to benchmark that specific piece of code. And not be a bonehead by doing it in debug mode.
Subramanyam ReddyPosted Jun 10, 2020, 12:28 AM
Nice article
Sateesh Kr MauryaPosted Jul 4, 2019, 5:29 AM
Any one have idea where create class object we can create global or in method
Sateesh Kr MauryaPosted Jul 4, 2019, 5:25 AM
That great
NathanPosted Feb 13, 2019, 11:17 PM
Not of it is correct either.
pawrv asdffPosted Feb 28, 2017, 10:25 AM
ALL, is wrong ALL is bullshit, you no idea what you doing. U second and 3rd are wrong from beginning you messure, is order of magnitude to big. Struck are NOT be general they are only better in few specific areas, in many cases they are slower than class. foreach is only few % slower than for, not 2 times. + operator is faster than stringBuldier if u add less than 4 elements. 1 is good because knowing structure make difference but u dont know array list is implemented and u did test wrong. If you init list size in costructor like you did in array it will be only few % slower. 5 will be optim ;), but in general case is faster.
Bob ComtestPosted Feb 19, 2017, 6:14 PM
Tip 5 is wrong, this is because you ran from the VS debugger. The compiler doesn't optimise when run from the debugger. If you run the exe outside Visual Studio and add a warmup loop at the start so that the JIT has time to work as well you get these results:warmup: 4Direct Assign: 1 Using Property: 1
Bikesh SrivastavaPosted Aug 22, 2016, 10:52 PM
Very nice
Narahari NallagatlaPosted Dec 14, 2015, 7:39 AM
very very good article.
shakilPosted Nov 27, 2015, 5:31 AM
good one
Prakash TripathiPosted Oct 7, 2015, 2:11 AM
Good article.
AJAY KUMAR SANTRAPosted May 20, 2015, 6:03 AM
Thanks for pretty good article. but for #Tip4, string is much faster then string Builder...
Pothappa KasenathPosted Apr 15, 2015, 5:54 AM
Well,i will follow from today
Jeffrey ZhouPosted Apr 6, 2015, 7:04 PM
For Tip#1 - The slow performance is NOT because List<int> stores it in object format but the Array.Copy, I think. Since you defines it as List<int>, it should store it in int format but object. That is to say, there is no additional boxing/unboxing operations.
Pankaj Kumar ChoudharyPosted Feb 17, 2015, 12:58 AM
Sir,This article is very good for begginers just like me.You discussed about time taking by for loop and foreach loop.You write that for loop is faster then Foreach loop.But accrording me it not always true it depend upon data type which you using. like for "Array" Foreach is faster Then For loop and for "List" For loop is faster then faster then Foreach
Levin GPosted Jan 8, 2015, 2:53 PM
You're right eric... accessing the array each time would then push down performance very much... look at this for greater understanding what to use: http://www.dotnetperls.com/for-foreach
Eric ColdwaterPosted Feb 27, 2014, 3:53 PM
In Tip #2, inside the for loop should be lst1.Add(Count[i]); instead of lst1.Add(i);. This would get the values from the Count list similar to what the foreach loop does. The Article Extension has this same problem.
Shweta LodhaPosted Feb 6, 2014, 3:35 PM
I usually prefer using For for high performance code :)
Ehsan MAPosted Feb 6, 2014, 2:56 PM
Hi Sourav, Thanks for pretty good article. Can you please explain why did you choosed a low number of itterations for measuring performance? for example i did raised the itterations on tip#5 to 1000000000 (1e9) from 100, and then the performance of assigning property and field was very near (~%25 difference). And can you explain the reason of this difference?
Santosh KumarPosted Oct 21, 2013, 6:49 AM
Thanks for providing such a nice information.
Vithal WadjePosted Oct 7, 2013, 1:32 PM
good one keep it up
liangde yePosted Jul 31, 2013, 2:57 AM
very good, thank you. but i think we shuld test property after it be used tirst time. because ,first time to user property(no matter get or set ) will cost more time .
ShantanuPosted Jul 26, 2013, 1:54 AM
thanks for sharing
Sonam SharmaPosted Jul 24, 2013, 2:26 AM
kudos for the article.depicts good practices.one should really follow
Nimit JoshiPosted Jul 10, 2013, 11:15 AM
Very Impresive...
Dhanik SahniPosted Jul 9, 2013, 5:25 AM
Good Post. Examples are good and easy to understand.
brajeshPosted Jul 2, 2013, 1:58 PM
Reverse for loop(max count to 0) is fastest then foreach and for loop
Goutam YadavPosted Jun 28, 2013, 9:09 AM
really nice!
Venkatesh KumarPosted Jun 28, 2013, 3:16 AM
i am not sure Foreach is better that For loop , which version of C# you have tested, Can we try with some other collection types also
Gabriel Espirito SantoPosted Jun 26, 2013, 8:42 AM
Very good sir, congratulations!
Harshal VadnerePosted Jun 26, 2013, 4:57 AM
nice post and it is very informative
Arvind PradhanPosted Jun 25, 2013, 11:45 AM
very good thought sir
Srinubabu RavillaPosted Jun 25, 2013, 7:59 AM
Nice article
Santosh ThakurPosted Jun 25, 2013, 6:38 AM
Great Tips..Very Helpful not only for Beginners but all developers........
Ravi ShekharPosted Jun 25, 2013, 6:27 AM
Very very informative...
Gowthamaprabhu SPosted Jun 25, 2013, 1:47 AM
Nice Article and Very useful Thanks
Sourav KayalPosted Jun 25, 2013, 12:28 AM
Dear Sandeep ,you are correct . Thanks to share this information with us.
Sourav KayalPosted Jun 25, 2013, 12:26 AM
Dear Sam, I am not saying that string is less efficient or bad . Just i have tried to show in which situation ,what need to use. And if we choose perfect option in perfect situation then only performance will increase.
Sandeep Singh ShekhawatPosted Jun 24, 2013, 10:05 PM
Nice article, Thanks Sourav!! Struct is a better than class because it is value type and no need boxing. But the size of struct is the sum of the sizes of its members and we define more members in struct then it will be get large. Then It will be create a problem and involved overhead when we passing its instance. Microsoft recommends that the size of a struct should ideally be below 16 bytes, but it really is up. So struct should use for lightweight objects not instead of class.
Sam HobbsPosted Jun 24, 2013, 4:47 PM
I agree that use of StringBuilder should be balanced with other criteria. I think one important point is that people that review other people's code should not automatically say that the string class is inefficient. The efficiency of the developer needs to be considered too. Note that the StringBuilder class does not have all the methods that the string class does. I do not understand why. I think that if the string class is not efficient then Microsoft needs to put all the methods that are in the string class in the StringBuilder class also.
Sourav KayalPosted Jun 24, 2013, 10:38 AM
Yes Sir, If there is huge string concatenation operation in development scenario then StringBuilder performs well.
Mahesh ChandPosted Jun 24, 2013, 8:57 AM
I've added an Article Extension. So if there are only a few operations on strings, StringBuilder may not be a good idea.
Sourav KayalPosted Jun 24, 2013, 8:53 AM
Thanks Mahesh Sir,
Sourav KayalPosted Jun 24, 2013, 8:52 AM
Dear Akella, 5 th test i again tested in Release mode and without attached debugger and there is no change in performance :)
Mahesh ChandPosted Jun 24, 2013, 8:51 AM
Welcome to C# Corner Saurav and great tips. Keep it up.
Jay ParekhPosted Jun 24, 2013, 8:08 AM
Very useful tips Thanks
Dinesh BeniwalPosted Jun 24, 2013, 7:00 AM
Great Start, Welcome to the C# Corner.
AkellaPosted Jun 24, 2013, 5:11 AM
in fifth test just change configuration to Release and run without attached debuger, you'l see the difference
AkellaPosted Jun 24, 2013, 5:09 AM
structure allocates memmory much faster than reference type (because stack and heap), but you can face with performance problem when needs to copying value types
AkellaPosted Jun 24, 2013, 5:06 AM
in first test change "new List<int>()" to "new List<int>(10000)" and run in Release w/o attached debugger
AkellaPosted Jun 24, 2013, 5:04 AM
running tests in debug configuration is unaccpetable
Dariush MoshiriPosted Jun 24, 2013, 4:07 AM
very useful
Akshatha SalianPosted Jun 24, 2013, 4:00 AM
Nice Article :) Thanks It Helped A Lot !!