I understand that the internal buffer used by IMemoryOwner<byte>.Memory can be larger than asked. But, is IMemoryOwner<byte>.Memory.Length defined with what I asked or with the size of the internal buffer ? The document seems not accurate enough.
Can MemoryPool<byte>.Rent(int minBufferSize ) capable of returning a IMemoryOwner<byte> bigger than asked?
1k views Asked by Perfect28 At
1
Let's take a look.
MemoryPool<T>.Rentis abstract, so we'll go looking for an implementation.ArrayMemoryPool<T>.Rentlooks like a good, representative candidate. That implementation looks like this:Let's chase that into
ArrayMemoryPoolBuffer:The
new Memory<T>(array)means thatMemory<T>.Lengthwill just be the size of the underlying array: we don't have any logic to have a smallerMemory<T>wrapping a larger array. So let's see ifArrayPool<T>.Shared.Rentgives us back an array of the correct size...Again this is abstract, but we can find an implementation at
ConfigurableArrayPool<T>. The meat of that method is:We can see that the pool has multiple buckets, with each bucket containing arrays of a specified size. This method is finding the bucket of arrays which are just larger than the requested size; if that bucket is empty it goes looking at larger buckets. If it fails to find anything, it creates a new array with the bucket size; only if the requested size is larger than the pool can manage does it create an array of the exact requested size.
So it's very unlikely that the array underlying the
Memory<T>has the requested size, and the construction of theMemory<T>does nothing to pretend that theMemory<T>is smaller than its underlying array.The conclusion is that
IMemoryOwner<byte>.Memory.Lengthcan indeed be larger than requested.