You could use MemoryMarshal API to perform very fast and efficient conversion. String
will implicitly be cast to ReadOnlySpan<byte>
, as MemoryMarshal.Cast
accepts either Span<byte>
or ReadOnlySpan<byte>
as an input parameter.
public static class StringExtensions
{
public static byte[] ToByteArray(this string s) => s.ToByteSpan().ToArray(); // heap allocation, use only when you cannot operate on spans
public static ReadOnlySpan<byte> ToByteSpan(this string s) => MemoryMarshal.Cast<char, byte>(s);
}
Following benchmark shows the difference:
Input: "Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s,"
| Method | Mean | Error | StdDev | Gen 0 | Gen 1 | Gen 2 | Allocated |
|----------------------------- |-----------:|----------:|----------:|-------:|------:|------:|----------:|
| UsingEncodingUnicodeGetBytes | 160.042 ns | 3.2864 ns | 6.4099 ns | 0.0780 | - | - | 328 B |
| UsingMemoryMarshalAndToArray | 31.977 ns | 0.7177 ns | 1.5753 ns | 0.0781 | - | - | 328 B |
| UsingMemoryMarshal | 1.027 ns | 0.0565 ns | 0.1630 ns | - | - | - | - |