Pages

Saturday, September 27, 2008

StringBuilder in .Net

There are small small things which can improve the performance of the code. When we are dynamically constructing SQL query in .Net application we declare a string variable and append the SQL to it.

Ex:

String sSQL = null;
sSQL += "SELECT Col1,Col2,Col3";
sSQL += " FROM Table_name ";
sSQL += " WHERE Col4 = 10 ";

This is not a good approach to deal with String because String is immutable. Therefore, every time when you concatenate the new value a new instance will be made and it will make a great performance loss if concatenation will be done many times.

Lets look at the best apporach

System.Text.StringBuilder sSQL = new System.Text.StringBuilder();
sSQL.Append(" SELECT Col1,Col2,Col3 ");
sSQL.Append(" FROM Table_name ");
sSQL.Append(" WHERE Col4 = 10 ");

So from now on try to use StringBuilder.

No comments: