Working with Strings in C#.NET

Strings, strings and strings. They are all over in your application. You cannot avoid them at all. This article is about some tips on how you should use strings within your application. Most developers know these tips, but I still see some developers write inefficient code.


Before we drill into much deeper, would you recommend using String over string? For example…

String apple;
string apple;

Not really, string is simply an alias (shorthand) for the Common Type System (CTS) System.String class, which represents a sequence of characters. You can use them interchangeably in your code. For example…

String x = string.Copy("x");
string y = String.Copy("y");
<b>String concatenations</b>

Often developer concatenate string using + operator. Some developer use StringBuilder class in System.Text namespace.

string concat = "Apple" + ", " + "Orange";

StringBuilder sb = new StringBuilder();
sb.Append(", ");

So which one you should be using? It depends. For example if you have few strings that need to concatenate, then ‘+’ operator would just be fine. However if you have so many of them, it is better to use the StringBuilder class. The reason is that direct string concatenation will always consume more memory as it creates String objects for every instance that it creates. On the other hand StringBuilder is a complex type, which require instantiating once (also take up a negligible start-up time), and Append method is much faster, better CPU and efficient memory usage. Because of the tiny start up cost of instantiating StringBuilder class, it is preferable to use ‘+’ operators for when concatenating only few strings.

Below is an excellent article on string concatenations performances

“The conclusion to be drawn from these test results is really very straightforward. You should be using the StringBuilder class for all but the most trivial string concatenation (or replace) operations. The extra effort required to use the StringBuilder class is negligible and is far outweighed by the potential performance and scalability benefits to be gained. ”

Empty Strings

<pre>string a = "";
string c = String.Empty;

There is no much performance differences on any of these. If you want the maximum efficiency and better use of CPU memory use String.Empty. String.Empty is a static and read only field. It does not create any object. Because when you use an empty string “”, it still creates a new object. If you are performing a string comparison with an empty string, for example…

if (testString == String.Empty)
     testString = "Test string is empty";

if (StringA.Equals(String.Empty))
     testString = "Test string is empty"; 

if (testString.Length == 0)
      testString = " Test string is empty";

Some of you would argue the lack of readabilty on Legth == 0, but the truth is the Length comparison is the most efficient. If you need to check for null or empty string then String.IsNullOrEmpty() is also better on performances.

Securing your strings
Common string classes in .NET framework store string in memory. If you are dealing with very sensitive data, then storing in memory is not the most secure way. For this you need to use SecureString class which is System.Secure name space.

System.Security.SecureString secureString = new System.Security.SecureString();

Unfortunately you cannot assign a string to the secure class. Please find more information on Secure String below.

Compare Strings
Many developers tend to use the case insensitivity to compare two strings. This is not really efficient when comparing two strings.

if (testStringA.ToUpper() == testStringB.ToUpper())
     // Your code goes here

The regular expression engine in .NET is extremely good. but is not the most efficient method of simply comparing two strings. The below code is bit of a overkill.

var pattern = "Regex pattern.";
var string_value = "Hi! This is a test.";
var b = Regex.IsMatch(string_value, pattern);
Console.WriteLine("{0}", b);

However there is a much efficient way to compare strings using String.Compare method.

if (String.Compare(testStringA, testStringB, true) == 0)
      // Your code goes here

The below comparison does the same thing, but it is the most efficient.

if (String.Equals(StringA, StringB, StringComparison.OrdinalIgnoreCase))
	// Your code goes here                

More information is on ordinal string comparison is below.

String Literals and String Constants
I mentioned previously that string literals create a new string object. It doesn’t mean that you should not be using string literals at all. For example using string literals directly in your code assist readability of your code and have better performance than using string constants. Having said that if you have number of strings being used in you code over and over again, it is still better to define the string constants as the performance gain I mentioned above is not really significant. As you know changing strings in many places is often painful than declare it once, and use it wherever and wherever you want is lot easier.

private const string testString = "sampleString";
StringA = testString;

StringA = “sampleString” //efficient

The above are some of the examples that I tried by my self to prove better and efficient way of string manipulations. However there are many other string manipulations techniques which I haven’t mentioned here and worth trying. For example splitting strings, replacing strings, removing strings etc. It is very easy to check these operations, and all you need is micro-benchmarking fascilty. I use System.Diagnostics.Stopwatch class for benchmarking but there are other techniqes as well.

As a final note always be mindful when perform codding, and use these techinques so you would write efficient C# code.

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s