Brian H. Madsen
Computer says no

C# Code tips #3, Strings

January 15th 2007 in 2101, 3118 As most of us has figured out, string comparison is a performance bottleneck – so why do we do it? Well, data is most often in a humanly friendly format (eg. we can read it), and secondly we need to manipulate data to display to an end-user – both cases which require string comparison and/or creation.

lets take this example, comparing two strings, say email addresses, which is passed in from a registration form:


Code:
private bool CompareEmailAddresses(string email1, string email2)
{
   return (email1 == email2);
}
or, alternatively, we want to ensure that two usernames are compare, with a business rule dictating that both strings the same case (here lower case).


Code:
private bool CompareUsernames(string username1, string username2)
{
   return (username1.ToLower() == username2.ToLower());
}
well – both sets of code does what it’s meant to do – namely, compare two strings and returning a true/false.

But is it effective?

no – not really, for instance, using either ToUpper() or ToLower() actually doesn’t change the current string, but actually returns a completely new string in the case requested. Logically that would not be effective in any way.

How do we know this – well i use a handy tool called FxCop (http://www.gotdotnet.com/Team/FxCop/), which will actually give you the following piece of information for the last string comparison method:


Quote:
“StringCompareTest.CompareUsername(String, String):Boolean calls String.op_Equality(String, String):Boolean after converting “stack1″, a local to upper or lowercase. If possible, eliminate the string creation and call the overload of String.Compare that performs a case-insensitive comparison.”
so how does that look:


Code:
private bool CompareUsernames(string username1, string username2)
{
   return (string.Compare(username1, username2, false, System.Globalization.CultureInfo.CurrentCulture) == 0);
}
There’s also other tools available out there today which will help you write effective code and/or performance tune you code. One such tool is NProf (http://www.mertner.com/confluence/display/NProf/Home) which is a .Net profiler.

Another snippet which is quite common is to check to see if your string is empty:


Code:
if (username1.Length != 0) {}
or


Code:
if (username1 != “”) {}
i’ve learned not to use either of those – granted i’ve probably been a culprit before.

personally i prefer to use:


Code:
if (string.IsNullOrEmpty(username1)) {}
or


Code:
if (username != string.Empty) {}

Anyways, google is your friend as there’s tons of tidbits out there which explains the ins and outs of performance tuning code and help you get your code habits on the right track…

4 comments to...
“C# Code tips #3, Strings”

jhowey

The one thing you should point out is that in your suggested methods, you do NOT run the risk of seeing a NullException thrown when you’re reading one of its properties/accessors if the string is NULL — in other words, your way is better.



BrianMadsen

jhowey,

that’s correct – forgot to mention that particular aspect of the examples.

thanks for pointing it out.

strangely enough, most developers care most about database optimisation as they see that as the main bottleneck of their application. I personally think it’s a mixture of both, since leaving one sloppy you end up doing optimisation work with no real gain.



jhowey

True, as if your code misbehaves in any way (bugs introduced by not bulletproofing your code; differences in the way you compare strings/objects; messy/unreadable/undocumented code from maintenance perspective), they will not stick around long enough to notice your optimizations.

Anyways, keep up the Code tips, as I personally seem to learn/remember something new every time.



BrianMadsen

jhowey,

that’s right – i go over often read articles and blog posts constantly to refresh knowledge i most likely have forgotten unless i apply it on a daily basis – besides, you’re never too old to (re)learn new/old tricks.

i’ll definitely keep them up – thanks for the encouraging words!




required



required - won't be displayed


Your Comment:

A new craze has found its way to me – Audiobooks and podcasts – my oldest daugther bought me another IPod for christmas (ok, my wife did since my daughter is only 3) and not one single piece of music has found its way onto it yet – but i use it all the time…i’ve [...]

Previous Entry

Back to Visual Studio again – it is afterall my personal favorite development GUI (go figure, durr!!).One of the few tricks to helping you out is how to create a tasklist – it can be useful if you get a call, just as you’re in the middle of some code, for a change to a [...]

Next Entry