Whe*_*ler 8 c# string performance byte
目前我正在使用此代码将字符串转换为字节数组:
var tempByte = System.Text.Encoding.UTF8.GetBytes(tempText);
Run Code Online (Sandbox Code Playgroud)
我经常在我的应用程序中调用此行,我真的想使用更快的行.如何将字符串转换为字节数组比默认的GetBytes方法更快?也许有一个不安全的代码?
Mag*_*tLU 10
如果您不太关心使用特定的编码,并且您的代码对性能至关重要(例如,它是某种数据库序列化程序,需要每秒运行数百万次),请尝试
fixed (void* ptr = tempText)
{
System.Runtime.InteropServices.Marshal.Copy(new IntPtr(ptr), tempByte, 0, len);
}
Run Code Online (Sandbox Code Playgroud)
编辑:Marshal.Copy大约快十倍,UTF8.GetBytes并获得UTF-16编码.要将其转换回字符串,您可以使用:
fixed (byte* bptr = tempByte)
{
char* cptr = (char*)(bptr + offset);
tempText = new string(cptr, 0, len / 2);
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2952 次 |
| 最近记录: |