Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c#

.net

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?

like image 542
Jack Wester Avatar asked Oct 07 '22 09:10

Jack Wester


1 Answers

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.

like image 143
dtb Avatar answered Oct 13 '22 10:10

dtb