Friday, October 05, 2007

C#.NET - Do you think StringBuilder is always the best way to Concatenate Strings? I don't think so!

Almost all the Microsoft C#.NET developers would have been told many times to use StringBuilder to concatenate strings. It is true that using StringBuilder improves performance of string concatenation operations. But it is not always true. There are few situations where StringBuilder perform slower than normal string concatenation operator +.

 

While concatenating 1 – 4 strings dynamically it is preferred to use string concatenation operator

Yes. while concatenating small number(1 to 4) of strings it is preferred to use string concatenation operator instead of StringBuilder.

This sample StringBuilder code took 2098 milliseconds to run on my PC

// Concatenate 3 strings using StringBuilder
for (int nCounter = 0; nCounter <= 9000000; nCounter++)
{            
  StringBuilder sbBuffer = new StringBuilder();
  sbBuffer.Append(nCounter.ToString());
  sbBuffer.Append(nCounter.ToString());
  sbBuffer.Append(nCounter.ToString());
}


The following sample code using + operator took slightly less amount of time 2001 milliseconds




// Concatenate 3 strings using + operator
for (int nCounter = 0; nCounter <= 9000000; nCounter++)
{
    string sBuffer = nCounter.ToString();
    sBuffer = nCounter + nCounter.ToString();
    sBuffer = nCounter + nCounter.ToString();
}


 


While building a string with known literals use + operator instead of StringBuilder


When we need to build to SQL statement or Java Script in C# code we need to concatenate many lines of SQL/Java Script code. While building strings with known literals it is preferred to use + instead of StringBuilder




// Build SQL script block
string sSQLBlock = "SELECT name, "
              + "age, dateofbirth "
              + "FROM Student WITH(NOLOCK)"
              + "WHERE name like 'A%'";

alternately you can even use @ operator




// Build SQL script block
string sSQLBlock = @"SELECT name, 
                    age, dateofbirth 
                     FROM Student WITH(NOLOCK)
                     WHERE name like 'A%'";

0 Comments: