快速字符串到字节[]的转换 [英] Fast string to byte[] conversion

查看:76
本文介绍了快速字符串到字节[]的转换的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当前,我正在使用以下代码将字符串转换为字节数组:

Currently I am using this code for converting string to byte array:

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

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

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

推荐答案

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

If you don't care too much about using specific encoding and your code is performance-critical (for instance it's some kind of DB serializer and needs to be run millions of times per second), try

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

编辑元帅.Copy UTF8.GetBytes 快十倍,并且可以使用UTF-16编码。要将其转换回字符串,可以使用:

Edit: Marshal.Copy was around ten times faster than UTF8.GetBytes and gets you UTF-16 encoding. For converting it back to string you can use:

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

这篇关于快速字符串到字节[]的转换的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆