I have some template string
this is my {0} template {1} string
which I plan to put user values in using String.Format()
.
The string actually is longer so for readability I use:
this is my {goodName1} template {goodName2} string
And then String.Replace
each parameter with its value.
How can I get the highest performance and readability?
Maybe I should not have this template in a file (as now) but dynamically build it by concatanating to a string builder and adding the params when required? Although it's less readable.
What's my other options?
You can put the parameters in a dictionary and use the Regex.Replace
method to replace all of the parameters in one replacement. That way the method scales well if the template string gets long or the number of parameters grows.
Example:
Dictionary<string, string> parameters = new Dictionary<string, string>();
parameters.Add("goodName1", "asdf");
parameters.Add("goodName2", "qwerty");
string text = "this is my {goodName1} template {goodName2} string";
text = Regex.Replace(text, @"\{(.+?)\}", m => parameters[m.Groups[1].Value]);
From Atwood: It. Just. Doesn't. Matter.
Like anything, it depends. If the code is going to be called millions of times every day, then think about performance. If it's a few times a day then go for readability.
I've done some benchmarking between using normal (immutable) strings and StringBuilder. Until you start doing a huge amount in small bit of time, you don't need to worry about it too much.
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