I am currently using the following snippet to write an UTF8 encoded string to a network stream in a performance critical section:
private static readonly ArrayPool<byte> POOL = ArrayPool<byte>.Shared;
private static readonly Encoding ENCODING = Encoding.UTF8;
private async ValueTask Write(string text)
{
var length = ENCODING.GetByteCount(text);
var buffer = POOL.Rent(length);
try
{
ENCODING.GetBytes(text, 0, length, buffer, 0);
await OutputStream.WriteAsync(buffer.AsMemory(0, length)).ConfigureAwait(false);
}
finally
{
POOL.Return(buffer);
}
}
My feeling is that this can be written more efficiently and maybe even allocation free using one of the Span<T> and Memory<T> based overloads, but I fail to see how.
My understanding would be that I can somehow convert the Span<char> representation of the string on the fly into something that I can pass to the stream (e.g. ReadOnlyMemory<byte> without the need to use an intermediate buffer (neither allocated nor rented) - so just by accessing the underlying bytes of the string (there is already memory allocated for them - why would I need to allocate new?).