代码之家  ›  专栏  ›  技术社区  ›  Mike Cole

优化我的方法

c#
  •  1
  • Mike Cole  · 技术社区  · 16 年前

    我正在尝试创建一个实用程序方法来对模板文件执行类似邮件合并的功能。因为字符串是不变的,所以我不确定是否写得正确——有人能看一眼并给我反馈吗?

    public static string LoadTemplateFile(string fileName, 
                                          NameValueCollection  mergeFields)
    {
        string result = System.IO.File.ReadAllText(fileName);
    
        if (mergeFields != null)
        {
            for (int index = 0; index < mergeFields.Count; index++)
            {
                result = result.Replace(mergeFields.Keys[index], 
                                        mergeFields[index]);
            }
        }
    
        return result;
    }
    
    3 回复  |  直到 16 年前
        1
  •  4
  •   JaredPar    16 年前

    你好像在试图

    1. 从磁盘读取文件
    2. 根据提供的名称/值映射进行搜索/替换

    如果是这样的话,那么是的,这就行了。

    唯一真实的反馈是,根据替换名称/值对的数量,您将创建大量临时字符串。对于小文件来说,这可能很好,但是一旦开始将相对大的文件加载到应用程序中,您可能会看到明显的差异。

    更好的方法是使用StringBuilder并对该对象执行replace调用。它将减少不必要的临时字符串创建。

        2
  •  10
  •   John Saunders    16 年前

    最好使用StringBuilder而不是String。

    public static string LoadTemplateFile(
        string fileName, NameValueCollection  mergeFields)
    {    
        System.Text.StringBuilder result = new System.Text.StringBuilder(
            System.IO.File.ReadAllText(fileName));
    
        if (mergeFields != null)
        {
            for (int index = 0; index < mergeFields.Count; index++)
            {
                result.Replace(mergeFields.Keys[index], 
                                        mergeFields[index]);
            }
        }
    
        return result.ToString();
    }
    
        3
  •  1
  •   Sergio    16 年前

    使用StringBuilder而不是String。这是我唯一的建议,它的方式更快。