Saturday, September 6, 2008

Writing Fast Code the easy way Part I


String or StringBuilder?


Which is better string or StringBuilder? We all know that StringBuilder is the better choice. Really? If yes, then by what ratio.

Let’s check it out.

We have following code blocks which perform exactly same, but are written in different ways

private const int LOOPCOUNT = 1000;

private void StringBuilderAppend()

{

StringBuilder _subElementValue = new StringBuilder();

int i = 0;

while (i++ <= LOOPCOUNT)

{

_subElementValue.Append("_xmlStart");

_subElementValue.Append("nav3Name");

_subElementValue.Append("_xmlEnd");

_subElementValue.Append("nav3.Value");

_subElementValue.Append("_xmlEndStart");

_subElementValue.Append("nav3Name");

_subElementValue.Append("_xmlEnd");

}

}

private void StringConcatenate()

{

int i = 0;

string sTemp = "";

while (i++ <= LOOPCOUNT)

{

sTemp += "_xmlStart";

sTemp += "nav3Name";

sTemp += "_xmlEnd";

sTemp += "nav3.Value";

sTemp += "_xmlEndStart";

sTemp += "nav3Name";

sTemp += "_xmlEnd";

}

}

As expected code block using StringBuilder.Append is quite fast compared to the string += operations. It’s 347 times faster than the string += operations! It’s a clear choice when concatenating multiple strings. What if we need the fastest code to be a little faster without killing the code readability and jumping into unsafe codes?

The following code is much faster than the StringBuilderAppend method. It’s faster by a factor of 2.4 times. What we simply did was used multiple string + operations (note there is no +=) and appended it in a StringBuilder.

private void StringBuilderAndStringConcatenate()

{

StringBuilder _subElementValue = new StringBuilder();

int i = 0;

while (i++ <= LOOPCOUNT)

{

_subElementValue.Append("_xmlStart" + "nav3Name" + "_xmlEnd" + "nav3.Value" + "_xmlEndStart" +

"nav3Name" + "_xmlEnd");

}

}



The above readings were generated with exact same code listed above and measured using DevPartner Performance expert. Its highly recommended that before applying any performance tips in your project, make sure to measure the performance yourself.

1 comment: