string str = 'my {0} long string {1} need formatting';
Should I be doing the following,
str = string.Format(str, "really", "doesn't");
or creating a method like so and calling str = str.ReplaceWithValues("really", "doesn't");
public string ReplaceWithValues(this string str, params object[] values) {
string ret = str;
for (int i = 0; i < values.Length; i++) {
ret = str.Replace(string.Concat("{", i, "}"), values.ToString());
}
return ret;
}
It seems like StringBuilder.AppendFormat() isn't efficient when it comes to doing simple replacements like this since it goes character by character through the string.
Why do you want to reinvent String.Format?
I'd just use the framework method - it does exactly what you want, is robust, and is going to make sense to those that follow...
Just to satisfy your curiousity:
It seems like StringBuilder.AppendFormat() isn't efficient when it comes to doing simple replacements like this since it goes character by character through the string.
String.Format, FYI, uses StringBuilder.AppendFormat internally. That being said, StringBuilder.AppendFormat is quite efficient. You mention that it goes "character by character" through the string - however, in your case, you're using multiple calls to Replace and Concat instead. A single pass through the string with a StringBuilder is likely to be much quicker. If you really need to know- you could profile this to check. On my machine, I get the following timings if I run both of the above 1,000,000 times:
String.Format - 1029464 ticks
Custom method - 2988568 ticks
The custom procedure will increase its cost with each additional placeholder and produce throwaway strings for the garbage collector with each intermediate call to Replace
.
Besides the likelihood that string.Format
is much faster than multiple calls to Replace
, string.Format
includes overloads to culture-sensitive operations as well.
The flexibility and intuitiveness of string.Format
is at least as compelling as the speed.
If all you want is to concatenate some strings, why not just do that?
string result = "my " + x + " long string " + y + " need formatting";
or
string result = string.Concat("my ", x, " long string ", y, " need formatting");
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With