我不完全确定我在测试中是否做错了什么,但从我的结果来看,MemoryPool 始终比 ArrayPool 慢并且分配更多内存,因为无论如何您都可以将 Array 类型转换为 Memory,那么使用 MemoryPool 有什么意义呢?
using System.Buffers;
using BenchmarkDotNet.Running;
using BenchmarkDotNet.Attributes;
BenchmarkRunner.Run<test>();
[MemoryDiagnoser]
public class test
{
[Benchmark]
public void WithArrayPool()
{
ArrayPool<int> pool = ArrayPool<int>.Shared;
for (int z = 0; z < 100; z++)
{
var memory = pool.Rent(2347);
for (int i = 0; i < memory.Length; i++)
{
memory[i] = i + 1;
}
int total = 0;
for (int i = 0; i < memory.Length; i++)
{
total += memory[i];
}
pool.Return(memory);
} …Run Code Online (Sandbox Code Playgroud)