Inefficient usage of string.format? I have some sample code where I used string.Format but after reading about benchmark performances by other people I believe that it may be better to do multiple appends by a StringBuilder

Here is the scenario:

In my gridView, I have a function called before a databind. The function looks like such:

public string getColumnText(String myParam)
{
    StringBuilder sb = new StringBuilder();
    return sb.Append(string.Format("&lt;a href='javascript:Global.someFunction(\"{0}\");'&gt;{1}&lt;/a&gt;", myParam).ToString();
}


Is this a better alternative?

StringBuilder sb = new StringBuilder();
sb.Append("&lt;a href = 'javascript:Global.someFunction(\"");
sb.Append(myParam"); etc...


Let's assume that this function will be called 10,000 times.
A StringBuilder is useful when you're constructing a string where a loop will be directly effecting it, i.e. if you were appending several strings together within a loop, I'd recommend using a StringBuilder. Here's an example of where you might use a StringBuilder.

StringBuilder sb = new StringBuilder()
for (int i = 0; i &lt; someItems.length; i++)
{
    sb.AppendFormat("{0} is item index {1}\n", someItems[i], i);
}
return sb.ToString();


There are some overheads with string.Format, however they aren't huge, especially not in your case. Unless you're concerned about micro-optimisations, I think in this scenario it all falls down to readability, and which you prefer.

An alternative method, which would be slightly faster than string.Format is to simply concatenate the string together, like so:

public string getColumnText(String myParam)
{
    return "&lt;a href='javascript:Global.someFunction(\"" + myParam + "\");'&gt;" + myParam + "&lt;/a&gt;";
}


You may also want to consider ensuring it's safe for your desired output, i.e. do you need to escape quotation marks for myParam, or does it need to be HTML encoded?