snippetcsharpMinor
Inefficient usage of string.format?
Viewed 0 times
usagestringformatinefficient
Problem
I have some sample code where I used
Here is the scenario:
In my
Is this a better alternative?
Let's assume that this function will be called 10,000 times.
string.Format but after reading about benchmark performances by other people I believe that it may be better to do multiple appends by a StringBuilderHere 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("{1}", 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.
Solution
A
There are some overheads with
An alternative method, which would be slightly faster than
You may also want to consider ensuring it's safe for your desired output, i.e. do you need to escape quotation marks for
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 "" + myParam + "";
}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?Code Snippets
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();public string getColumnText(String myParam)
{
return "<a href='javascript:Global.someFunction(\"" + myParam + "\");'>" + myParam + "</a>";
}Context
StackExchange Code Review Q#20230, answer score: 5
Revisions (0)
No revisions yet.