在模板中替换字符串的最快方法

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)


Agi*_*Jon 17

来自阿特伍德:它.只是.不.物.

  • 不得不反对 - 这很重要.只是*确保*在优化之前很重要,而不是假设. (21认同)
  • 有时它确实很重要......就像在这种情况下,将Replace从20秒调整到0.1 ...... http://www.codeproject.com/Articles/298519/Fast-Token-Replacement-in-Csharp (4认同)

Iai*_*der 7

喜欢什么,这取决于.如果代码每天都会被调用数百万次,那就考虑一下性能.如果它是一天几次,那么为了可读性.

我在使用普通(不可变)字符串和StringBuilder之间做了一些基准测试.直到你在很短的时间内开始大量工作,你不必太担心它.


Fre*_*örk 7

我的自发解决方案看起来像这样:

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)

我在几个真实项目中使用过这种模板替换,但从未发现它是性能问题.由于它易于使用和理解,我没有看到任何改变它的理由.


Abh*_*der 5

刚刚将上面的答案修改为以下内容:

    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)

希望这可以帮助.. :)