快速字符串到byte 的转换

目前我使用此代码将字符串转换为字节数组:

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

我经常在我的应用程序中调用此行,我真的想使用更快的行。 如何将字符串转换为字节数组比默认的GetBytes方法更快? 也许有一个不安全的代码?

如果您不太关心使用特定的编码,并且您的代码对性能至关重要(例如,它是某种数据库序列化程序,需要每秒运行数百万次),请尝试

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

编辑Marshal.CopyUTF8.GetBytesUTF8.GetBytes并获得UTF-16编码。 要将其转换回字符串,您可以使用:

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