在C#中附加两个或多个字节数组 [英] Append two or more byte arrays in C#
问题描述
是否有最好的方法(见下文)在C#中附加两个字节数组?
Is there a best (see below) way to append two byte arrays in C#?
假装我有完全的控制权,则可以使第一个字节数组足够大以在末尾保留第二个字节数组,并使用
Pretending I have complete control, I can make the first byte array sufficiently large to hold the second byte array at the end and use the Array.CopyTo function. Or I can loop over individual bytes and make an assignment.
还有更好的方法吗?我无法想象像将字节数组转换为字符串并将它们连接起来再转换回它们之类的方法会比上面的任何一种方法都要好.
Are there better ways? I can't imagine doing something like converting the byte arrays to string and joining them and converting them back would be better than either method above.
关于最佳/更好(按顺序):
In terms of best/better (in order):
- 最快
- 最低RAM消耗
一个约束是我必须在.NET 2.0框架中工作.
A constraint is that I must work in the .NET 2.0 framework.
推荐的两个选择是MemoryStream和BlockCopy.我已经对10,000,000个循环进行了3次简单的速度测试,并得到以下结果:
The two choices recommended are MemoryStream and BlockCopy. I have run a simple speed test of 10,000,000 loops 3 times and got the following results:
- 块复制时间:1154 ,范围为13毫秒
- MemoryStream GetBuffer时间:1470,范围为14毫秒
- MemoryStream ToArray时间:1895,范围为3毫秒
- 复制到时间:2079,范围为19毫秒
- 逐字节时间:2203,范围为10毫秒
- BlockCopy Time: 1154, with a range of 13 milliseconds
- MemoryStream GetBuffer Time: 1470, with a range of 14 milliseconds
- MemoryStream ToArray Time: 1895, with a range of 3 milliseconds
- CopyTo Time: 2079, with a range of 19 milliseconds
- Byte-by-byte Time: 2203, with a range of 10 milliseconds
列表结果< byte> AddRange 超过一千万个循环: List< byte>时间:16694
Results of List<byte> AddRange over 10 million loops: List<byte> Time: 16694
- 逐字节:1
- BlockCopy:1
- 复制到:1
- MemoryStream GetBuffer:2.3
- MemoryStream ToArray:3.3
- 列表< byte>:4.2
- Byte-by-byte: 1
- BlockCopy: 1
- Copy To: 1
- MemoryStream GetBuffer: 2.3
- MemoryStream ToArray: 3.3
- List<byte>: 4.2
该测试表明,通常来说,除非您要进行很多字节拷贝[我是],否则查看字节拷贝是不值得关注的.一千万次跑步最多相差1.1秒].
The test shows that in general, unless you are doing a lot of byte copies [which I am], looking at byte copies is not worth a focus [e.g. 10 million runs yielding a difference of as much as 1.1 seconds].
推荐答案
您要 BlockCopy
根据此博客文章,它速度更快比Array.CopyTo.
According to this blog post it is faster than Array.CopyTo.
这篇关于在C#中附加两个或多个字节数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!