Вы находитесь на странице: 1из 8

In Focus ANNOUNCEMENT: C# Corner Annual Conference 2016 Dates Announced Navanath

Ask a Question Contribute

Basics of AngularJS: Part 1 C#CornerSearch

ARTICLE READER LEVEL:

5 Tips to Improve Performance of C# Code


By Sourav Kayal on Jun 24, 2013

In this article I show you 5 best practices of C# programming.

76.9 k 45 6

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. TRENDING UP
1. Choose your data type before using it
01 Introduction to Web Service with
Example in ASP.NET
For many types we prefer to not decide what data type to use in our daily programming life. Even a few
monthsago 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
02 Basics of AngularJS: Part 1

this concept.
03 Microsoft Build 2015 Top Highlights:
Day 1 Keynote
staticvoid Mainstring[] args
{
List<Int32> li = new List<int>; 04 Google+ Authentication in ASP.Net

Stopwatch sw =new Stopwatch;


sw.Start;

05 How to Configure SharePoint Server in
Windows Azure
for int i = 0; i < 10000; i++
{ 06 How to Create Nodejs Module and
Publish Over to Npm
li.Addi;
}
sw.Stop;
07 Basics of AngularJS: Part 2


Console.Write"Using ArraylistObject" + sw.ElapsedTicks + "\n"; 08 Microsoft Build 2015 Top Highlights:
Day 2 Keynote
sw.Reset;

sw.Start;
09 Learn Simple MVVM and Command
Bindings in 15 Mins
Int32[] a = new Int32[10000];
for int i = 0; i < 10000; i++ 10 jQuery Validation Plugin to Validate
Web Forms
{
a[i] = i; View All
}
sw.Stop;
Console.Write"Using ValueInteger Array" + sw.ElapsedTicks; Follow@csharpcorner 17.6Kfollowers

Console.ReadLine;
FindusonFacebook
}
C#Corner
Like

89,303peoplelikeC#Corner.
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.

2. 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 loopis 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.Addi;
}

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

Console.Write"For Loop : "+ sw.ElapsedTicks+"\n";
sw.Restart;

foreach int a in Count
{
lst2.Adda;
}
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.

3. 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 Mainstring[] 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 toget the programto astable 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 variableis stored.
And a class objectis a reference type. In case of an object type the reference is created and the valueis
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 memoryin this fashion, generally it will take more time
than a structure variable.

4. 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 Mainstring[] 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.

5. Choose best way to assign class data member


TECHNOLOGIES ANSWERS BLOGS VIDEOS INTERVIEWS BOOKS NEWS CHAPTERS CAREER ADVICE JOBS
Before assigning a value to your class variable, Isuggest you look at the following code and output screenat
this point.

namespace Test
{
public classTest
{
public staticstring Name { get;set; }
public staticString surname;
}
class Program
{
static void Mainstring[] 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.

ARTICLE EXTENSIONS
Contents added by Sam Hobbs on Jul 13, 2013
Download File: Part0Step2.zip

The following is an alternative sample of Step 2. This sample executes the two loops more than once; three
times each. I get varying results each time of the three times and each time I execute this sample. I think
these samples are not the most definitive evidence of efficiency.

usingSystem;
usingSystem.Collections.Generic;
usingSystem.Diagnostics;

namespacePart0Step2
{
classProgram
{
staticvoidMain(string[]args)
{
List<Int32>Count=newList<int>();
for(inti=0;i<10000;i++)
{
Count.Add(i);
}
UseFor(Count);
UseForeach(Count);
UseFor(Count);
UseForeach(Count);
UseFor(Count);
UseForeach(Count);
}

privatestaticvoidUseFor(List<int>Count)
{
List<Int32>lst1=newList<Int32>();
Stopwatchsw=Stopwatch.StartNew();
sw.Start();
for(inti=0;i<Count.Count;i++)
{
lst1.Add(i);
}
sw.Stop();
Console.WriteLine("ForLoop:"+sw.ElapsedTicks);
}

privatestaticvoidUseForeach(List<int>Count)
{
List<Int32>lst2=newList<Int32>();
Stopwatchsw=Stopwatch.StartNew();
sw.Start();
foreach(intainCount)
{
lst2.Add(a);
}
sw.Stop();
Console.WriteLine("ForeachLoop:"+sw.ElapsedTicks);
}
}
}

As I said, the results vary each time I execute this sample but the following shows the results of one run:

I really think that code reviewers and Quality Assurance personnel need to consider developer efficiency. A
foreach loop can often be a greater utilization of the developer's time.

Contents added by Mahesh Chand on Jun 24, 2013


Here are two articles. First is related to when using a String vs a StringBuilder. Also the "using" keyword is
very useful and good programming practice. Check out these two articles.

Compare String and StringBuilder


Leveraging the using keyword

Sourav Kayal
I am .NET learner passionate logger, like to .NET eat and sleep. Have little experience in
Web technology with new development platform including node.js, MVC Web API. Feel
free to teach me .NET.

Personal Blog:http://ctrlcvprogrammer.blogspot.com

Rank 2.3m Platinum 2


25 Readers Member Times

RELATED ARTICLES
Tips to Improve the Performance of ASP.Net Tips to improve the performance in ASP.Net
Application application
ASP.NET Performance Practices Improve Performance of Word 2013
Using Regions to Improve Code Readability Visual studio and .NET tips and tricks 13:-
Increase performance of IF condition
Streamlining Web Application Performance Generic DAL using WCF: Part 6
Generic Dal in WCF using VB.NET Using Regions to Improve Code Readability

COMMENTS View Previous Comments >> 10 of 45

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 .
liangde ye Jul 31, 2013

634 1 0 0 0 Post Reply


good one keep it up
Vithal Wadje Oct 07, 2013
21 6k 4m 0 0 Post Reply

Thanks for providing such a nice information.


Santosh Kumar Oct 21, 2013

393 265 282.3k 0 0 Post Reply

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 (~% difference). And can you explain the reason of this difference?
Ehsan MA Feb 06, 2014

634 1 0 0 0 Post Reply

I usually prefer using For for high performance code :)


Shweta Lodha Feb 06, 2014

71 2.2k 169.5k 0 0 Post Reply

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.
Eric Coldwater Feb 27, 2014

634 1 0 1 0 Post Reply

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
Levin G Jan 08, 2015

634 1 0 0 0 Post Reply

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
Pankaj Kumar Choudhary Feb 17, 2015

271 541 18.8k 0 0 Post Reply

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.
Jeffrey Zhou Apr 06, 2015

634 1 0 0 0 Post Reply

Well,i will follow from today


Pothappa Kasenath Apr 15, 2015

634 1 0 0 0 Post Reply

Type your comment here and press Enter Key....

Follow Comments

COMMENT USING
12comments Addacomment

AndreasGrabnerTechnologyStrategistatDynaTrace
Greatpost!!Ijustworkedwithac#teamandwefoundsomeotherinterestingperformancekillers:
String.Concat,WrongSizingofWorkerThreads,ExcessiveSQLExecutions,ExcessiveDBConnection
HandlingandHighGCcausedbyloadingtoomuchdataintomemory.Incaseyouareinterested:http://
apmblog.compuware.com/2015/01/14/cperformancemistakestopproblemssolveddecember/
ReplyLikeFollowPostJanuary14at8:08pm

HansHernndezInstitutoNacionalSanLuis
Nicepost!ItriedgetthedifferencebetweenuseaList<T>andCollection<T>,Accordingtothe
documentationit'smorerecommendedtouseCollection<T>thanList<T>forpublicAPIS,butIgeta
surprise!,takesmoreresourcestocreateaCollection<T>of10000elementsthanaList<T>of10000
elements,Idon'tknowwhyofthisdifference...
ReplyLikeFollowPostAugust29,2014at9:04am

CsharpCorner Follow221followers
PostyourQuestionintheForumssectionofthesitehereisthelinkhttp://www.c
sharpcorner.com/Forums/
ReplyLikeEditedAugust29,2014at12:43pm

NanaYaw FollowKellerGraduateSchoolofManagement
Nicearticle.Thanks.However,howcometip2defeatsthepurposeoftip1?easeofuse?oryourlovefor
listisendless.=)
ReplyLikeFollowPostDecember4,2013at1:32pm

AlokRanjanTiwariSoftwareEngineerTrainee(IOS)atTechAheadSoftware
nice
ReplyLikeFollowPostSeptember3,2013at5:30pm

HaoranHenryYiWorksatNationalInstruments
InterestingresultonC#performance.
ReplyLikeFollowPostJune25,2013at3:19am

View5more

Facebooksocialplugin

MVPs MOST VIEWED LEGENDS NOW PRIZES REVIEWS SURVEY CERTIFICATIONS DOWNLOADS Hosted By CBeyond Cloud Services

PHOTOS CODE SNIPPETS CONSULTING TRAINING STUDENTS MEMBERS MEDIA KIT ABOUT US LINKS IDEAS

CONTACT US PRIVACY POLICY TERMS & CONDITIONS SITEMAP REPORT ABUSE

2015 C# Corner. All contents are copyright of their authors.

Вам также может понравиться