Eyl*_*ylM 6 c# performance string-formatting
我一直在我的 C# 项目中进行一些代码重构。我收到了 Resharper 代码分析警告:
“冗余字符串插值”
这发生在以下场景中:
void someFunction(string param)
{
...
}
someFunction($"some string");
Run Code Online (Sandbox Code Playgroud)
我读过字符串插值string.Format
在编译时被重写。然后我尝试了以下操作:
someFunction(string.Format("some string"));
Run Code Online (Sandbox Code Playgroud)
这次我得到:
冗余 string.Format 调用。
我的问题是:除了代码清洁度之外,这些冗余调用是否会影响运行时性能,或者性能是否相同:
someFunction($"some string")
someFunction("some string")
someFunction(string.Format("some string"))
Run Code Online (Sandbox Code Playgroud)
作为C# 编译器中特定优化的作者,我可以确认C# 编译器$"some string"
对此进行了优化。"some string"
这是一个常量,因此实际上不需要在运行时执行任何代码来计算它。
另一方面,string.Format("some string")
是方法调用,并且该方法必须在运行时调用。显然,该调用会产生相关成本。当然,它不会做任何有用的事情,因此会出现警告“冗余字符串.格式调用”。
更新:事实上,编译器始终将不带填充的插值优化为结果字符串。它所做的只是 unescape {{
to{
和}}
to }
。我的更改是优化插值,其中所有填充都是字符串,而不格式化为字符串连接。
好吧,让我们执行一个基准测试:
private static long someFunction(string value) {
return value.Length;
}
...
Stopwatch sw = new Stopwatch();
int n = 100_000_000;
long sum = 0;
sw.Start();
for (int i = 0; i < n; ++i) {
// sum += someFunction("some string");
// sum += someFunction($"some string");
sum += someFunction(string.Format("some string"));
}
sw.Stop();
Console.Write(sw.ElapsedMilliseconds);
Run Code Online (Sandbox Code Playgroud)
结果(.Net 4.8 IA-64 版本),平均结果:
224 // "some string"
225 // $"some string"
8900 // string.Format("some string")
Run Code Online (Sandbox Code Playgroud)
所以我们可以看到,编译器删除了不需要的$
但执行的内容string.Format
,这浪费了时间来理解我们没有任何格式