Why is allocation the same for the given methods?
[Benchmark(Baseline = true)]
public bool Any()
{
return _persons.Any(x => x.Id == _id);
}
[Benchmark]
public bool FirstOrDefault()
{
var entity = _persons.FirstOrDefault(x => x.Id == _id);
return entity is not null;
}
Results:
| Method | Size | Mean | Error | StdDev | Ratio | Gen0 | Allocated | Alloc Ratio |
|--------------- |----- |---------:|--------:|--------:|------:|-------:|----------:|------------:|
| Any | 10 | 113.3 ns | 0.22 ns | 0.20 ns | 1.00 | 0.0166 | 104 B | 1.00 |
| FirstOrDefault | 10 | 113.5 ns | 0.51 ns | 0.46 ns | 1.00 | 0.0166 | 104 B | 1.00 |
I thought that FirstOrDefault
should allocate more because the record is created.
1