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?
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);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With