gpt4 book ai didi

c# - 在 C# 中使用丢弃运算符 "_"是否以任何方式优化代码?

转载 作者:太空狗 更新时间:2023-10-30 01:12:36 25 4
gpt4 key购买 nike

例如,假设我调用这个方法:

return bool.TryParse(s, out _);

这是否比这样调用更有效:

return bool.TryParse(s, out var dummy);

?

最佳答案

让我们不要相信任何东西并使用 BenchmarkDotNet 进行测量。

这是我的代码:

using System;
using BenchmarkDotNet.Attributes;
using BenchmarkDotNet.Running;

namespace Measure
{
public static class Program
{
static void Main(string[] args) => BenchmarkRunner.Run(typeof(Program).Assembly);
}

public class Bench
{
[Params("true", "false", "invalid")] public string Input { get; set; }

[Benchmark]
public bool IsBoolWithVariable() => bool.TryParse(Input, out var result);

[Benchmark]
public bool IsBoolDiscarding() => bool.TryParse(Input, out _);
}
}

结果如下:

|             Method |   Input |      Mean |     Error |    StdDev |
|------------------- |-------- |----------:|----------:|----------:|
| IsBoolWithVariable | false | 7.483 ns | 0.0069 ns | 0.0058 ns |
| IsBoolDiscarding | false | 7.479 ns | 0.0040 ns | 0.0034 ns |
| IsBoolWithVariable | invalid | 15.802 ns | 0.0051 ns | 0.0043 ns |
| IsBoolDiscarding | invalid | 15.838 ns | 0.0043 ns | 0.0038 ns |
| IsBoolWithVariable | true | 7.055 ns | 0.0053 ns | 0.0047 ns |
| IsBoolDiscarding | true | 7.104 ns | 0.0407 ns | 0.0381 ns |

看起来没有区别。让我们看看它是否编译为相同的 IL:

IsBoolDiscarding():

    IL_0000: ldarg.0      // this
IL_0001: call instance string Measure.Bench::get_Input()
IL_0006: ldloca.s V_0
IL_0008: call bool [System.Runtime]System.Boolean::TryParse(string, bool&)
IL_000d: ret

IsBoolWithVariable():

    IL_0000: ldarg.0      // this
IL_0001: call instance string Measure.Bench::get_Input()
IL_0006: ldloca.s result
IL_0008: call bool [System.Runtime]System.Boolean::TryParse(string, bool&)
IL_000d: ret

所以,没有任何区别。

关于c# - 在 C# 中使用丢弃运算符 "_"是否以任何方式优化代码?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57794028/

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