Tuesday, September 16, 2008

C# : Strings (Part 1)

Strings are immutable, so to perform a lot of string manipulations efficiently, use the StringBuilder class.

Having strings as immutable means there are no threads synchronization issues.
Also CLR can share multiple identical String contents through a single String object - String interning

String class is sealed.

To compare string without culture information use :
StringComparision.Ordinal or StringComparision.OrdinalIgnoreCase -- fastest.

Instead of lowercase, convert strings to uppercase using ToUpperInvariant()
Microsoft has optimized the code for performing uppercase comparision. In fact, the FCL normalizes strings to uppercase prior to performing case-insensitive comparisions.

Your code will be easier to read and maintain it you always indicate how you want to perform your string comparisions.

Strings cannot actually be changed--only new ones can be created. Therefore, Replace will repeatedly create new strings. StringBuilder, however, can be changed internally and no new copies will be created on Replace or Insert, so if you need to replace or insert very often, use StringBuilder

Given two string variables, how can one get both string variables to point to the same memory location?

No comments: