string + string 或 string + char 哪个更好?

what better string + string or string + char?

我有

    String Spaces = "";

并循环。在性能和代码风格方面有什么更好的? Spaces += ' ';Spaces += " "?

如果要创建 string 的实例,其中特定字符重复特定次数,则根本不需要循环。 There is a constructor for that.

在性能方面,我使用以下简单基准测试发现构造函数为您提供最佳性能。

using System;
using System.Text;

namespace SpaceStringCreationBench
{
   class Program
   {
      static void Main(string[] args)
      {
         int length = 100000;
         var watch = System.Diagnostics.Stopwatch.StartNew();
         BuildByAppendingString(length);
         watch.Stop();
         Console.WriteLine($"BuildByAppendingString: {watch.Elapsed}");

         watch.Restart();
         BuildByAppendingChar(length);
         watch.Stop();
         Console.WriteLine($"BuildByAppendingChar: {watch.Elapsed}");

         watch.Restart();
         BuildWithStringBuilder(length);
         watch.Stop();
         Console.WriteLine($"BuildWithStringBuilder: {watch.Elapsed}");

         watch.Restart();
         BuildWithCtor(length);
         watch.Stop();
         Console.WriteLine($"BuildWithCtor: {watch.Elapsed}");
      }

      static string BuildByAppendingString(int length)
      {
         string value = "";
         for (int i = 0; i < length; i++)
         {
            value += " ";
         }
         return value;
      }

      static string BuildByAppendingChar(int length)
      {
         string value = "";
         for (int i = 0; i < length; i++)
         {
            value += ' ';
         }
         return value;
      }

      static string BuildWithStringBuilder(int length)
      {
         StringBuilder sb = new StringBuilder(length);
         for (int i = 0; i < length; i++)
         {
            sb.Append(" ");
         }
         return sb.ToString();
      }

      static string BuildWithCtor(int length)
      {
         return new string(' ', length);
      }
   }
}

/*
Output:
BuildByAppendingString: 00:00:01.0523856
BuildByAppendingChar: 00:00:01.0380273
BuildWithStringBuilder: 00:00:00.0013483
BuildWithCtor: 00:00:00.0001228
*/

至于风格,嗯...我认为您会从不同的人那里得到不同的答案,但对于这样的事情,我认为构造函数是可行的方法。

所有这些都假设您生成的 string 的长度不同。如果您每次 运行 这个过程只需要相同数量的空格并且它的数量相当小,只需实例化 string。例如,如果您只需要一个包含五个空格的 string,只需执行以下操作:

string spaces = " ";