Console.Write(i)
在每个 for
或 Console.Write(StringBuilder)
末尾:哪个更好?
我有两个函数,第一个在 for 循环内打印,另一个在末尾打印。
public static void checkmethod1(int value, Checkevent text)
{
Stopwatch stopwatch2 = new Stopwatch();
stopwatch2.Start();
StringBuilder builder = new StringBuilder();
switch (text)
{
case Checkevent.odd:
for (int i = 1; i <= value; i = i + 2)
{
builder.Append(i).Append(" ");
}
break;
case Checkevent.even:
for (int i = 2; i <= value; i = i + 2)
{
builder.Append(i).Append(" ");
}
break;
}
stopwatch2.Stop();
Console.WriteLine(builder);
Console.WriteLine("{0}", stopwatch2.Elapsed);
}
函数2:
public static void checkmethod3(int value, Checkevent text)
{
Stopwatch stopwatch2 = new Stopwatch();
stopwatch2.Start();
switch (text)
{
case Checkevent.odd:
for (int i = 1; i <= value; i = i + 2)
{
Console.Write(i);
}
break;
case Checkevent.even:
for (int i = 2; i <= value; i = i + 2)
{
Console.Write(i);
}
break;
}
stopwatch2.Stop();
Console.Write("{0}", stopwatch2.Elapsed);
}
最佳答案
在这个特定的场景中,我更喜欢 StringBuilder
因为循环不会花费大量时间来改变用户体验。 StringBuilder 通常需要更少的内存,并且您将获得更好的性能。当您每次修改字符串 new string
时对象已创建,但 StringBuilder
的情况并非如此.
第一个方法执行 Console.Write
仅一次,但第二次将执行次 for
循环迭代。这将使第二个变慢。
如果您想在控制台中向用户显示文本,当您希望用户看到文本时,就像您正在显示日志以查看流程一样,那么显示一次(使用 StringBuilder
)可能不会给用户阅读的机会它。在这种情况下,您将写入使用 Console.Write(string)
生成的日志。 .
决定何时使用string
以及何时使用StringBuilder
当您了解两者的工作原理时,一切都会变得容易。他们的重要行为之一如下所示。
Using the StringBuilder Class in the .NET Framework
The String object is immutable. Every time you use one of the methods in the System.String class, you create a new string object in memory, which requires a new allocation of space for that new object. In situations where you need to perform repeated modifications to a string, the overhead associated with creating a new String object can be costly. The System.Text.StringBuilder class can be used when you want to modify a string without creating a new object. For example, using the StringBuilder class can boost performance when concatenating many strings together in a loop.
编辑
我用三个值 100、10000 和 100000 测试了上述两种方法,所使用的机器具有以下规范
Operating System: Windows 7 Enterprise and CPU
Processor: Intel(R) Core (TM) i5-3570 CPU @ 3.40 GHz 3.40 GHz
Installed memory (RAM): 8.00 GB
System Type: 64 bit Operating System
值 100
Time with StringBuilder 00:00:00.0000184
Time without StringBuilder 00:00:00.0037037
值 10000
Time with StringBuilder 00:00:00.0013233
Time without StringBuilder 00:00:00.2970272
值 100000
Time with StringBuilder 00:00:00.0133015
Time without StringBuilder 00:00:02.5853375
在第一个方法中,您使用了 StringBuilder
Console.Write
仅执行一次,但在其他情况下,它会执行与循环迭代一样多的次数。这使得第二个变慢。 将 StringBuilder 与字符串连接进行比较在这里不适用。
关于c# - 每个 for 中的 Console.Write(i) 或最后的 Console.write(Stringbuilder) 哪个更好,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30882310/