Home
    Shop
    Advertise
    Write For Us
    Affiliate
    Newsletter
    Contact

Strings Performance In ASP.NET

Strings are very important, you probably started to learn programming by using a strings, to build famous "Hello World!" application. After that, you probably noticed that string manipulation is one of the most used programming techniques in real world applications, especially in web programming.

 

Optimizing string concatenation

String concatenation is often used by ASP.NET developer to build XML, HTML or SQL code dynamically. There are two common ways to concatenate strings in .NET Framework, by using operators & or + and by using StringBuilder class.

String Concatenation by using an operator + or &

You can concatenate strings on standard way by using + or & operator, with code like this:

[ C# ]

private string CreateContactsXML(int ContactsTotal)
{
 // Create an XML by using + operator
 string ContactsXML = "";
 int i = 0;
 for (i = 1; i <= ContactsTotal; i++)
 {
   ContactsXML += "<Contact ContactID=\""
    + i.ToString() + "\" FirstName=\""
    + "FirstName"
    + "\" LastName=\""
    + "LastName"
    + "\" Email=\""
    + "my@email.com"
    + "\" City=\""
    + "My City"
    + "\"/>";
 }
 return ContactsXML;
}

[ VB.NET ]

Private Function ContactsXML(ByVal ContactsTotal As Integer) As String
  ' Create an XML by using + operator
  Dim i As Integer = 0
  ContactsXML = ""
  For i = 1 To i <= ContactsTotal
    ContactsXML &= "<Contact ContactID=\""" _
    & i.ToString() + """ FirstName=""" _
    & "FirstName" _
    & """ LastName=""" _
    & "LastName" _
    & """ Email=""" _
    & "my@email.com" _
    & """ City=""" _
    & "My City" _
    & """/>"
  Next
  Return ContactsXML
End Function

 

Note that code above is not doing anything smart, it just creates long string.

String Concatenation by using a StringBuilder class

Another way to build strings is by using a specialized StringBuilder class, with code like this:

[ C# ]

private string ContactsXMLWithStringBuilder(int ContactsTotal)
{
 // Create an XML by using string builder class
 StringBuilder sbContactsXML = new StringBuilder();
 int i = 0;
 for (i = 1; i <= ContactsTotal; i++)
 {
   sbContactsXML.Append("<Contact ContactID=\"");
   sbContactsXML.Append(i.ToString());
   sbContactsXML.Append("\" FirstName=\"");
   sbContactsXML.Append("FirstName");
   sbContactsXML.Append("\" LastName=\"");
   sbContactsXML.Append("LastName");
   sbContactsXML.Append("\" Email=\"");
   sbContactsXML.Append("my@email.com");
   sbContactsXML.Append("\" City=\"");
   sbContactsXML.Append("My City");
   sbContactsXML.Append("\"/>");
 }
 return sbContactsXML.ToString();
}

[ VB.NET ]

Private Function ContactsXMLWithStringBuilder(ByVal ContactsTotal As Integer) As String
  ' Create an XML by using + operator
  Dim i As Integer = 0
  Dim sbContactsXML As StringBuilder = New StringBuilder()
  For i = 1 To i <= ContactsTotal
    sbContactsXML.Append("<Contact ContactID=\""")
    sbContactsXML.Append(i.ToString())
    sbContactsXML.Append(""" FirstName=""")
    sbContactsXML.Append("FirstName")
    sbContactsXML.Append(""" LastName=""")
    sbContactsXML.Append("LastName")
    sbContactsXML.Append(""" Email=""")
    sbContactsXML.Append("my@email.com")
    sbContactsXML.Append(""" City=""")
    sbContactsXML.Append("My City")
    sbContactsXML.Append("""/>")
  Next
  Return sbContactsXML.ToString()
End Function

 

Note: To use StringBuilder class you need to import System.Text namespace.

So, should I use operators + and & or StringBuilder class?

StringBuilder is generally faster because string is immutable and every action on string actually create new string. That uses a lot of memory. But StringBuilder is complex class and instantiate of StringBuilder type will take some time too. Because of that, you can use standard way with + and & operators if you concatenate just a few strings. If number of strings is higher (e.g. few hundreds), then you should consider StringBuilder way. In general, if you work with some long while or for loop you better use StringBuilder's Append method since it is faster, with less memory requirements and less CPU usage. Of course, the fastest solution is to not use concatenation at all :). If you can avoid it on some way that is usually best solution.

Difference between String.Empty and ""

This difference is not big, but if you want to get maximum efficiency use String.Empty because String.Empty does not create an object. "" creates an object, so it is probably better to write code like this:

[ C# ]

if (StringToCompare == String.Empty)
{
    // Your code goes here
}

[ VB.NET ]

If StringToCompare = String.Empty Then
  ' Your code goes here
End If

 

There is another way, even better than String.Empty. Instead of any comparing of strings, you can just check string length. This will be fastest solution, like this:

[ C# ]

if (StringToCompare.Length == 0)
{
    // Your code goes here
}

[ VB.NET ]

If StringToCompare.Length = 0 Then
  ' Your code goes here
End If

Comparing strings (case insensitive)

Easiest way for case insensitive comparation of two strings is by using ToLower() or ToUpper() method, and many developers do so. The code with ToUpper() method would look like this:

[ C# ]

if (String1.ToUpper() == String2.ToUpper())
{
    // Your code goes here
}

[ VB.NET ]

If String1.ToUpper = String2.ToUpper Then
  ' Your code goes here
End If

 

However, there is much more efficient way for case insensitive strings comparing by using Compare() method:

[ C# ]

if (String.Compare(String1, String2, true) == 0)
{
    // Your code goes here
}

[ VB.NET ]

If String.Compare(String1, String2, True) = 0 Then
  ' Your code goes here
End If

 

Second approach with String.Compare method much more faster than ToLower() or ToUpper() method and without high demands to garbage collector.

Comparing strings (case sensitive)

When comparing strings, developers usually use = operator in VB.NET or == operator in C#. There is significant difference between C# operator == and VB.NET operator =. == is much faster than =. If you are C# programmer, you can continue to use = operator and performance will be ok. Of course, if you are VB.NET programmer, you can't use == operator. But, you can use String.Equals method to get better results. Code could look like this:

[ VB.NET ]

If String.Equals(String1, String2) Then
  ' Strings are equal
End If

SecureString

SecureString class is located in System.Secure namespace. Common classes String and StringBuilder stores data in memory as plain text. If your string contains sensitive data this could be security problem. In that case, you should consider SecureString class. This class encrypts data automatically by using DPAPI (Data Protection API). Unfortunately, we can't assign a string to SecureString directly, but we can use its AppendCharacter method to add character by character. For example, to assign word "hello" code would be:

[ C# ]

System.Security.SecureString SecretString =
    new System.Security.SecureString();
SecretString.AppendChar('H');
SecretString.AppendChar('e');
SecretString.AppendChar('l');
SecretString.AppendChar('l');
SecretString.AppendChar('o');

[ VB.NET ]

Dim SecretString As System.Security.SecureString = _
  New System.Security.SecureString()
SecretString.AppendChar("H")
SecretString.AppendChar("e")
SecretString.AppendChar("l")
SecretString.AppendChar("l")
SecretString.AppendChar("o")

 

There is an interesting method MakeReadOnly(). After calling this method it is not possible to add new characters. If you try to add another character SecureString will throw exception. To return a string from SecureString when you need it, use this code:

[ C# ]

using System.Runtime.InteropServices;
 
...
 
IntPtr pSecureString = Marshal.SecureStringToBSTR(SecureString);
string MyPlainPassword = Marshal.PtrToStringUni(pSecureString);

[ VB.NET ]

Imports System.Runtime.InteropServices
 
...
 
Dim pSecureString As IntPtr = Marshal.SecureStringToBSTR(SecureString)
Dim MyPassword As String = Marshal.PtrToStringUni(pSecureString)


Tutorial toolbar:  Tell A Friend  |  Add to favorites  |  Feedback  |   Google


comments powered by Disqus