是和不是。
调用简单委托不会在堆上分配任何东西,但创建委托会在堆上分配 64 个字节。
为了避免 GC,您可以预先创建委托。
让我们验证一下:
using BenchmarkDotNet.Running;
namespace Test
{
class Program
{
static void Main(string[] args)
{
var summary = BenchmarkRunner.Run<BenchmarkDelegate>();
}
}
}
基准:
using BenchmarkDotNet.Attributes;
namespace Test
{
[MemoryDiagnoser]
public class BenchmarkDelegate
{
public delegate int GetInteger();
GetInteger _delegateInstance;
public BenchmarkDelegate()
{
_delegateInstance = WithoutDelegate;
}
[Benchmark]
public int WithInstance() => RunDelegated(_delegateInstance);
[Benchmark]
public int WithDelegate() => RunDelegated(WithoutDelegate);
public int RunDelegated(GetInteger del) => del();
[Benchmark]
public int WithoutDelegate() => 0;
}
}
以下输出,向右滚动以查看 分配的内存/操作列:
DefaultJob : .NET Core 2.2.1 (CoreCLR 4.6.27207.03, CoreFX 4.6.27207.03), 64bit RyuJIT
| Method | Mean | Error | StdDev | Gen 0/1k Op | Gen 1/1k Op | Gen 2/1k Op | Allocated Memory/Op |
|---------------- |-----------:|----------:|----------:|------------:|------------:|------------:|--------------------:|
| WithInstance | 7.5503 ns | 0.0751 ns | 0.0702 ns | - | - | - | - |
| WithDelegate | 35.4866 ns | 1.0094 ns | 1.2766 ns | 0.0203 | - | - | 64 B |
| WithoutDelegate | 0.0000 ns | 0.0000 ns | 0.0000 ns | - | - |
- | - |