快速字符串到byte []转换

时间:2013-11-28 19:27:34

标签: c# string performance byte

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

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

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

1 个答案:

答案 0 :(得分:10)

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

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

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

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