gpt4 book ai didi

c# - 快速字符串到 byte[] 的转换

转载 作者:太空狗 更新时间:2023-10-29 18:27:02 26 4
gpt4 key购买 nike

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

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.GetBytes 快大约十倍,并且让您获得 UTF-16 编码。要将其转换回字符串,您可以使用:

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

关于c# - 快速字符串到 byte[] 的转换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20273556/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com