gpt4 book ai didi

c# - 在 C# 中附加字符串与 char 之间是否有任何惩罚

转载 作者:IT王子 更新时间:2023-10-29 04:30:09 25 4
gpt4 key购买 nike

几年前在使用 Java 进行开发时,我了解到如果我有一个字符而不是一个具有一个字符的字符串,最好附加一个字符,因为 VM 不必对中的字符串值进行任何查找它的内部字符串池。

string stringappend = "Hello " + name + "."; 
string charappend = "Hello " + name + '.'; // better?

当我开始使用 C# 编程时,我从未想过它与它的“VM”一样的可能性。我遇到了C# String Theory—String intern pool这表明 C# 也有一个内部字符串池(我想如果没有的话会很奇怪)所以我的问题是,

在连接到关于 C# 的字符串时,附加一个 char 而不是字符串实际上有什么好处,还是它只是胡言乱语?

编辑:请忽略 StringBuilder 和 string.Format,我更感兴趣的是为什么我要替换“.”和 '。'在代码中。我很清楚那些类和函数。

最佳答案

如果可以选择,我会在调用 System.String.Concat 或(等价的)时传递 string 而不是 char + 运算符。

我看到的System.String.Concat 的唯一重载都采用字符串或对象。由于 char 不是字符串,因此将选择对象版本。这将导致 char 被装箱。在 Concat 验证对象引用不为 null 之后,它会在 char 上调用 object.ToString。然后,在创建新的连接字符串之前,它会生成最初被避免的可怕的单字符字符串。

所以我看不出传递一个字符会有什么好处。

也许有人想看看Reflector中的Concat操作,看看对char有没有特殊处理?

更新

如我所想,这个测试证实 char 稍微慢一些。

using System;
using System.Diagnostics;

namespace ConsoleApplication19
{
class Program
{
static void Main(string[] args)
{
TimeSpan throwAwayString = StringTest(100);
TimeSpan throwAwayChar = CharTest(100);
TimeSpan realStringTime = StringTest(10000000);
TimeSpan realCharTime = CharTest(10000000);
Console.WriteLine("string time: {0}", realStringTime);
Console.WriteLine("char time: {0}", realCharTime);
Console.ReadLine();
}

private static TimeSpan StringTest(int attemptCount)
{
Stopwatch sw = new Stopwatch();
string concatResult = string.Empty;
sw.Start();
for (int counter = 0; counter < attemptCount; counter++)
concatResult = counter.ToString() + ".";
sw.Stop();
return sw.Elapsed;
}

private static TimeSpan CharTest(int attemptCount)
{
Stopwatch sw = new Stopwatch();
string concatResult = string.Empty;
sw.Start();
for (int counter = 0; counter < attemptCount; counter++)
concatResult = counter.ToString() + '.';
sw.Stop();
return sw.Elapsed;
}
}
}

结果:

string time: 00:00:02.1878399
char time: 00:00:02.6671247

关于c# - 在 C# 中附加字符串与 char 之间是否有任何惩罚,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3388128/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com