C# 替换模板中字符串的最快方法
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/959940/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
fastest way to replace string in a template
提问by Yaron Naveh
I have some template string
我有一些模板字符串
this is my {0} template {1} string
这是我的{0}模板{1}字符串
which I plan to put user values in using String.Format()
.
我计划将用户价值放在 using 中String.Format()
。
The string actually is longer so for readability I use:
字符串实际上更长,所以为了可读性,我使用:
this is my {goodName1} template {goodName2} string
这是我的 {goodName1} 模板 {goodName2} 字符串
And then String.Replace
each parameter with its value.
然后String.Replace
每个参数及其值。
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?
我的其他选择是什么?
采纳答案by AgileJon
From Atwood: It. Just. Doesn't. Matter.
来自阿特伍德:它。只是。没有。事情。
回答by Iain Holder
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.
我在使用普通(不可变)字符串和 StringBuilder 之间做了一些基准测试。在您开始在短时间内完成大量工作之前,您无需过多担心。
回答by Fredrik M?rk
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.
我在几个实际项目中使用过这种模板替换,但从未发现它是一个性能问题。由于它易于使用和理解,因此我没有看到任何对其进行大量更改的理由。
回答by Guffa
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.
您可以将参数放在字典中,并使用该Regex.Replace
方法在一次替换中替换所有参数。如果模板字符串变长或参数数量增加,则该方法可以很好地扩展。
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]);
回答by Joel Coehoorn
The fastestway to do it is with a StringBuilder using individual calls to StringBuilder.Append()
, like this:
该最快做到这一点的方式是使用个人来电StringBuilder的StringBuilder.Append()
,就像这样:
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 willbe fastest. If you want to improve readability you could keep a separate string to show the user, and just use this in the background.
我已经对框架代码进行了彻底的基准测试,这将是最快的。如果你想提高可读性,你可以保留一个单独的字符串来显示用户,并在后台使用它。
回答by jrista
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.
如果您需要一个好的、快速但简单的模板引擎,您应该查看 StringTemplate。对于模板本身不需要任何逻辑或流程控制的简单模板,StringTemplate 非常有用。
回答by Bobby Ortiz
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.
谨防陷入这种思维的泥潭。除非这段代码每分钟运行数百次并且模板文件有几 K 大小,否则完成它更为重要。不要浪费一分钟思考这样的问题。通常,如果您经常使用字符串操作,请使用字符串生成器。它甚至有一个 Replace 方法。但是,何必呢。完成后,如果发现有性能问题,请使用 PerfMon 并解决当时的真正瓶颈。
回答by jaxxbo
The same thing above that Fredrick posted above, but with linq.
Fredrick 在上面发布的内容相同,但使用 linq。
public static string FindandReplace(this string inputText, Dictionary<string, string> placeHolderValues)
{
if (!string.IsNullOrEmpty(inputText))
{
return placeHolderValues.Keys.Aggregate(inputText, (current, key) => current.Replace(key, placeHolderValues[key]));
}
else return inputText;
}
回答by Abhilash Shamsunder
Just modified the above answer to the following:
刚刚将上述答案修改为以下内容:
string data = "This is a {template1} that is {template2}.";
Dictionary<string, string> replacements = new Dictionary<string, string>(){
{"{template1}", "car"},
{"{template2}", "red"},
};
data.Parse(replacements);
Extension method:
扩展方法:
public static class Parser
{
public static string Parse(this string template, Dictionary<string, string> replacements)
{
if (replacements.Count > 0)
{
template = replacements.Keys
.Aggregate(template, (current, key) => current.Replace(key, replacements[key]));
}
return template;
}
}
Hope this helps.. :)
希望这可以帮助.. :)