Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

fastest way to replace string in a template

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?

like image 777
Yaron Naveh Avatar asked Jun 06 '09 15:06

Yaron Naveh


3 Answers

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]);
like image 187
Guffa Avatar answered Oct 17 '22 15:10

Guffa


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

like image 36
AgileJon Avatar answered Oct 17 '22 15:10

AgileJon


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.

like image 7
Iain Holder Avatar answered Oct 17 '22 15:10

Iain Holder