Fast string to byte[] conversion

byte, c#, performance, string

Solution

If you don't care too much about using specific encoding and your code is performance-critical (for instance it's some kind of DB serializer and needs to be run millions of times per second), try

fixed (void* ptr = tempText)
{
    System.Runtime.InteropServices.Marshal.Copy(new IntPtr(ptr), tempByte, 0, len);
}

Edit: `Marshal.Copy` was around ten times faster than `UTF8.GetBytes` and gets you UTF-16 encoding. For converting it back to string you can use:

fixed (byte* bptr = tempByte)
{
    char* cptr = (char*)(bptr + offset);
    tempText = new string(cptr, 0, len / 2);
}

Problem

Currently I am using this code for converting string to byte array: ``` var tempByte = System.Text.Encoding.UTF8.GetBytes(tempText); ``` I call this line very often in my application, and I really want to use a faster one. How can I convert a string to a byte array faster than the default GetBytes method? Maybe with an unsafe code?

Original source

Related problems