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?
My spontaneous solution would look like this:
I have used this kind of template replacements in several real-world projects and have never found it to be a performance issue. Since it's easy to use and understand, I have not seen any reason to change it a lot.
BEWARE of getting bogged down with this type of thinking. Unless this code is running hundreds of time per minute and the template file is several K in size, it is more important to get it done. Do not waste a minute thinking about problems like this. In general, if you are doing a lot with string manipulations, then use a string builder. It even has a Replace method. But, why bother. When you are done, and IF you find that you have a performance problem, use PerfMon and fix the REAL bottlenecks at that time.
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.
Just modified the above answer to the following:
Extension method:
Hope this helps.. :)
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:
The fastest way to do it is with a StringBuilder using individual calls to
StringBuilder.Append()
, like this:I've thoroughly benchmarked the framework code, and this will be fastest. If you want to improve readability you could keep a separate string to show the user, and just use this in the background.