Yar*_*veh 15 c# string performance
我有一些模板字符串
这是我的{0}模板{1}字符串
我计划将用户值放入使用中String.Format()
.
字符串实际上更长,所以为了便于阅读我使用:
这是我的{goodName1}模板{goodName2}字符串
然后String.Replace
每个参数都有其值.
如何获得最高性能和可读性?
也许我不应该在文件中使用此模板(如现在),但通过连接到字符串生成器并在需要时添加参数来动态构建它?虽然它的可读性较差.
我的其他选择是什么?
Guf*_*ffa 41
您可以将参数放在字典中,并使用该Regex.Replace
方法替换一个替换中的所有参数.这样,如果模板字符串变长或参数数量增加,该方法可以很好地扩展.
例:
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]);
Run Code Online (Sandbox Code Playgroud)
喜欢什么,这取决于.如果代码每天都会被调用数百万次,那就考虑一下性能.如果它是一天几次,那么为了可读性.
我在使用普通(不可变)字符串和StringBuilder之间做了一些基准测试.直到你在很短的时间内开始大量工作,你不必太担心它.
我的自发解决方案看起来像这样:
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."
Run Code Online (Sandbox Code Playgroud)
我在几个真实项目中使用过这种模板替换,但从未发现它是性能问题.由于它易于使用和理解,我没有看到任何改变它的理由.
刚刚将上面的答案修改为以下内容:
string data = "This is a {template1} that is {template2}.";
Dictionary<string, string> replacements = new Dictionary<string, string>(){
{"{template1}", "car"},
{"{template2}", "red"},
};
data.Parse(replacements);
Run Code Online (Sandbox Code Playgroud)
扩展方法:
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;
}
}
Run Code Online (Sandbox Code Playgroud)
希望这可以帮助.. :)
归档时间: |
|
查看次数: |
18932 次 |
最近记录: |