Main Menu
Blog About MeProjects Web Design
Software Templates
Links Personal
Photography Other
Contacts
Since I’m writing my Master’s degree thesis on topic related to design and analysis of .NET static code (CIL), I had a chance to take a deeper look in those C# code fragments which are compliant with Microsoft recommendations and those which are not, and compare their performance.
Here is a short review of 3 popular “bad” and “good” programming habits.
String res = String.Empty; String app = "ABC"; for (int iCount = 0; iCount < 1000; iCount++) res = res + app; return res;
String res = String.Empty; String app = "ABC"; StringBuilder b = new StringBuilder(); for (int iCount = 0; iCount < 1000; iCount++) b.Append(app); return b.ToString();
Result ["bad" vs "good"]:
• Execution time (seconds): 1.63701196660469 vs 0.0429683102181981
• Memory usage (bytes): 3,038,054 vs 33,532
As we can see from the results you should always use StringBuilder class for string manipulation.
if (x.ToLower() == "geras")
if (String.Compare(x, "geras", true) == 0)
Result ["bad" vs "good"]:
• Execution time (seconds): 0.198623009348954 vs 0.136355039537148
• Memory usage (bytes): 19,020 vs 19,596
The increase of “good” code performance is apparent, but it will consume more RAM.
int i = 15; int j = 25;
Console.Write(“{0},{1}”, i, j);
int i = 15;
int j = 25;
Console.Write("{0},{1}", i.ToString(), j.ToString());
Result ["bad" vs "good"]:
• Execution time (seconds): 0.00588817852548299 vs 0.0114441919294212
• Memory usage (bytes): 25,038 vs 24,934
Even though the “good” code performs not as good as a “bad” code, but it will not require calling “box/unbox” operations, thus uses less memory.
Tags: blog, c#, habits, programming
Welcome to my homepage. I’m Ramunas Geciauskas, 24-year software engineer, computer programmer, web developer and designer based in Kaunas, Lithuania.
Hi, Very interesting article. I am quite impressed and just wanted to let you know that you did a fine job on this article. However, I do have some unanswered questions that I would like to ask you. I will contact you via email so that you can clear some of these things up for me. Again, very well written article. Keep up the good work.
I really like when people are expressing their opinion and thought. So I like the way you are writing
Do you have copy writer for so good articles? If so please give me contacts, because this really rocks!
Nice article. Though im aware and use all the syntaxes in this article, i never noticed one method was faster than the other. So i guess that means using c# conventions is better than that of traditional c.