views:

681

answers:

8

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?

A: 

I've just answered a similar question for Java, maybe the solution would help you.

laginimaineb
+5  A: 

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.

IainMH
I agree with Iain. For more information check out this article on Code Project: http://www.codeproject.com/KB/string/string.aspx
Kane
+2  A: 

My spontaneous solution would look like this:

string data = "This is a {template1} that is {template2}.";

Dictionary<string, string> replacements = new Dictionary<string, string>(){
    {"{template1}", "car"},
    {"{template2}", "red"},
};

foreach (string key in replacements.Keys)
{
    data = data.Replace(key, replacements[key]);
}
Console.WriteLine(data); // outputs "This is a car that is red."

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.

Fredrik Mörk
+2  A: 

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 teplate 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.Value]);
Guffa
This solution is the most performant, you should use an extension method of some sort to take care of non-existant keys when looking up the dictionary though.
Yann Schwartz
And \{([^}]+)\} is faster than using the non-greedy operator.
Yann Schwartz
+1  A: 

The fastest way to do it is with a StringBuilder using individual calls to StringBuilder.Append(), like this:

string result = new StringBuilder("this is my ")
                 .Append(UserVar1)
                 .Append(" template ")
                 .Append(UserVar2)
                 .Append(" string")
                 .ToString();

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.

Joel Coehoorn
+3  A: 

From Atwood: It. Just. Doesn't. Matter.

AgileJon
A: 

If you need a good, fast, but simple template engine, you should check out StringTemplate. For simple templates that don't require any logic or flow control in the template itself, StringTemplate is GREAT.

http://www.stringtemplate.org/download.html

jrista
+2  A: 

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.

Bobby Ortiz