【问题标题】:what better string + string or string + char?什么更好的字符串+字符串或字符串+字符?
【发布时间】:2021-04-07 19:55:09
【问题描述】:

我有

    String Spaces = "";

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

【问题讨论】:

  • 如果您在 loop 中添加空间(这就是您遇到性能问题的原因),请尝试 StringBuilderAppend
  • 根据我的测试,两者都编译为相同的 IL。编译器将它们都转换为字符串。如果您尝试将内容列表转换为字符串,您可能需要使用string.Join(" ", list)
  • 初始化 StringBuilder 是否比 String 需要更多时间?而且,我需要返回字符串。在这种情况下使用 StringBuilder 是否合理(否则我会在转换和初始化上浪费更多时间)?
  • 您正在执行循环以创建具有一定数量空格字符的string?你知道这个循环要执行多少次迭代吗?
  • @Титан:你能提供更多[相关]代码吗?您在哪里遇到性能问题?

标签: c# string char


【解决方案1】:

如果您想创建一个具有特定字符重复特定次数的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 = " ";

【讨论】:

    猜你喜欢
    • 2022-01-21
    • 1970-01-01
    • 2016-09-15
    • 2020-12-18
    • 1970-01-01
    • 1970-01-01
    • 2021-12-17
    • 2012-11-04
    • 1970-01-01
    相关资源
    最近更新 更多