Good/Bad C# Programming Habits

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.

“Bad” code:

String res = String.Empty;
String app = "ABC";

for (int iCount = 0; iCount < 1000; iCount++)
  res = res + app;

return res;

“Good” code:

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.


“Bad” code:

if (x.ToLower() == "geras")

“Good” code:

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.


“Bad” code:

int i = 15;

int j = 25;

Console.Write(“{0},{1}”, i, j);

“Good” code:

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: , , ,

February 1st, 2010 | Category: programming. | RSS 2.0 | Link

Leave a Reply

About Me

Welcome to my homepage. I’m Ramunas Geciauskas, 24-year software engineer, computer programmer, web developer and designer based in Kaunas, Lithuania.

The Best of Web

Digg.comSlashdot.orgGentoo.orgGnome.org

W3.orgnasa.gov/apodSecurityfocus.comDeveloper.com

Copyright © Ramunas Geciauskas. 2006-2009. All Rights Reserved.
Valid XHTML 1.1 Strict & CSS & RSS
Terms & Conditions | /proc/admin | About Me | /dev/null