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("<a href='javascript:Global.someFunction(\"{0}\");'>{1}</a>", myParam).ToString();
}
Is this a better alternative?
StringBuilder sb = new StringBuilder();
sb.Append("<a href = 'javascript:Global.someFunction(\"");
sb.Append(myParam"); etc...
Let's assume that this function will be called 10,000 times.
1 Answer 1
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 < 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 "<a href='javascript:Global.someFunction(\"" + myParam + "\");'>" + myParam + "</a>";
}
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?
-
\$\begingroup\$ I disagree, string.Format is much easier for my eyes too parse. Having a concatenated mess of variables and text is hard to look at and a pain to manage down the road. \$\endgroup\$Chuck Conway– Chuck Conway2013年01月08日 21:11:29 +00:00Commented Jan 8, 2013 at 21:11
-
\$\begingroup\$ I agree; I didn't imply using string concatenation with
+
was easier to read, I said it was slightly faster. I personally preferstring.Format
for readability. \$\endgroup\$Richard– Richard2013年01月09日 09:25:54 +00:00Commented Jan 9, 2013 at 9:25
gridview.databind()
is called so implying that 10K cooresponds to the number of entries in my gridView \$\endgroup\$