Is there a .NET StringBuilder that uses UTF-8 directly?

.net, c#

Solution

The MemoryStream is like a StringBuilder for bytes; you can use it to create a sequence of bytes efficiently by repeatedly appending sequences of bytes to it. It doesn't have methods to append strings of characters though. To avoid converting each string to a byte array first, you can wrap the stream in a StreamWriter which takes care of the conversion.

Problem

I have a performance sensitive scenario where I would like to write UTF-8 to a byte array. A quick glimpse on the .NET StringBuilder class has me believe that it only builds UTF-16 natively. Encoding.UTF8.GetBytes(str) means extra allocations and extra clock cycles that I am not willing to spend. Is there a native UTF-8 writer?

Original source