Fast string to byte conversion []

I am currently using this code to convert a string to an array of bytes:

var tempByte = System.Text.Encoding.UTF8.GetBytes(tempText); 

I use this line very often in my application, and I really want to use a faster one. How to convert a string to an array of bytes faster than the default GetBytes method? Maybe with unsafe code?

+6
source share
1 answer

If you donโ€™t care too much about using a particular encoding and your code is performance critical (for example, itโ€™s a kind of database serializer and should 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 about ten times faster than UTF8.GetBytes and got the UTF-16 encoding. To convert it to a string, you can use:

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

Source: https://habr.com/ru/post/959002/


All Articles