C# - 非常慢的字符串变量计算

时间:2018-04-12 17:59:45

标签: c# string performance

我在数组中有超过27,000,000个字符串变量。当我将一个字符串添加到另一个时,速度会大大降低。我的代码是:

 //public string[] part2 = { .....
 string Str1;
 string Str0;
 Parallel.ForEach(index_choose, x =>
         {
             Str1 += part1[x];
             Str0 += part2[x];

            //progressBar1.PerformStep();
            //label1.Text = progressBar1.Value.ToString();
            //Application.DoEvents();
        });
string total = Str1 + Str0;

在功能强大的CPU上运行此代码需要20多个小时!

1 个答案:

答案 0 :(得分:3)

我建议使用StringBuilder - 如下例所示

StringBuilder str0 = new StringBuilder();
StringBuilder str1 = new StringBuilder();
Parallel.ForEach(index_choose, x =>
         {
             Str1.Append(part1[x]);
             Str0.Append(part2[x]);

        //progressBar1.PerformStep();
        //label1.Text = progressBar1.Value.ToString();
        //Application.DoEvents();
    });
string total = Str1.Append(Str0).ToString();