使用ASCII字符编码在C#中将字符串转换为byte []数组的最快方法(性能方面) [英] Quickest way (performance-wise) to turn a string into a byte[] array in C# using the ASCII character encoding

查看:162
本文介绍了使用ASCII字符编码在C#中将字符串转换为byte []数组的最快方法(性能方面)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在C#中将字符串转换为byte []数组的最快方法是什么?我正在通过套接字发送大量的字符串数据,并且需要优化每个操作.目前,我在使用以下命令发送之前将字符串转换为byte []数组:

What's the fastest way to turn a string into a byte[] array in C#? I'm sending tonnes of string data through sockets and need to optimize every single operation. Currently I transform the strings in to byte[] arrays before sending using:

private static readonly Encoding encoding = new ASCIIEncoding();
//...
byte[] bytes = encoding.GetBytes(someString);
socket.Send(bytes);
//...

推荐答案

如果您的所有数据都是真正的 ASCII码,那么您可以比ASCIIEncoding稍快一些,它具有各种(完全合理的)错误处理等位.您也可以通过避免始终创建新的字节数组来加快处理速度.假设您有一个上限,所有消息都将位于该上限以下:

If all your data is really going to be ASCII, then you may be able to do it slightly faster than ASCIIEncoding, which has various (entirely reasonable) bits of error handling etc. You may also be able to speed it up by avoiding creating new byte arrays all the time. Assuming you have an upper bound which all your messages will be under:

void QuickAndDirtyAsciiEncode(string chars, byte[] buffer)
{
    int length = chars.Length;
    for (int i = 0; i < length; i++)
    {
        buffer[i] = (byte) (chars[i] & 0x7f);
    }
}

然后您将执行以下操作:

You'd then do something like:

readonly byte[] Buffer = new byte[8192]; // Reuse this repeatedly
...
QuickAndDirtyAsciiEncode(text, Buffer);
// We know ASCII takes one byte per character
socket.Send(Buffer, text.Length, SocketFlags.None);

这是非常绝望的优化.我会坚持使用ASCIIEncoding,直到我证明这是瓶颈(或者至少是这种讨厌的骇客无济于事).

This is pretty desperate optimisation though. I'd stick with ASCIIEncoding until I'd proven that this was the bottleneck (or at least that this sort of grotty hack doesn't help).

这篇关于使用ASCII字符编码在C#中将字符串转换为byte []数组的最快方法(性能方面)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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