永发信息网

c#byte数组高效复制怎么做

答案:2  悬赏:20  手机版
解决时间 2021-03-04 13:35
c#byte数组高效复制怎么做
最佳答案
在日常编程过程中,我们可能经常需要Copy各种数组,一般来说有以下几种常见的方法:Array.Copy,IList<T>.Copy,BinaryReader.ReadBytes,Buffer.BlockCopy,以及System.Buffer.memcpyimpl,由于最后一种需要使用指针,所以本文不引入该方法。

本次测试,使用以上前4种方法,各运行1000万次,观察结果。

using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;

namespace BenchmarkCopyArray
{
class Program
{
private const int TestTimes = 10000000;
static void Main()
{
var testArrayCopy = new TestArrayCopy();
TestCopy(testArrayCopy.TestBinaryReader, "Binary.ReadBytes");
TestCopy(testArrayCopy.TestConvertToList, "ConvertToList");
TestCopy(testArrayCopy.TestArrayDotCopy, "Array.Copy");
TestCopy(testArrayCopy.TestBlockCopy, "Buffer.BlockCopy");
Console.Read();
}

private static void TestCopy(Action testMethod, string methodName)
{
var stopWatch = new Stopwatch();
stopWatch.Start();
for (int i = 0; i < TestTimes; i++)
{
testMethod();
}
testMethod();
stopWatch.Stop();
Console.WriteLine("{0}: {1} seconds, {2}.", methodName, stopWatch.Elapsed.Seconds, stopWatch.Elapsed.Milliseconds);
}
}

class TestArrayCopy
{
private readonly byte[] _sourceBytes = new byte[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };

public void TestBinaryReader()
{
var binaryReader = new BinaryReader(new MemoryStream(_sourceBytes));
binaryReader.ReadBytes(_sourceBytes.Length);
}

public void TestConvertToList()
{
IList<byte> bytesSourceList = new List<byte>(_sourceBytes);
var bytesNew = new byte[_sourceBytes.Length];
bytesSourceList.CopyTo(bytesNew, 0);
}

public void TestArrayDotCopy()
{
var bytesNew = new byte[_sourceBytes.Length];
Array.Copy(_sourceBytes, 0, bytesNew, 0, _sourceBytes.Length);
}

public void TestBlockCopy()
{
var bytesNew = new byte[_sourceBytes.Length];
Buffer.BlockCopy(_sourceBytes, 0, bytesNew, 0, _sourceBytes.Length);
}
}
}
全部回答
以下是我写的一个函数,将两个不为空的byte数组合并: public static byte[] copybyte(byte[] a, byte[] b) { byte[] c = new byte[a.length + b.length]; a.copyto(c, 0); b.copyto(c, a.length); return c; } 不知道我理解的对不对,你的a[1]和a[2]都应该是数组吧?
我要举报
如以上问答信息为低俗、色情、不良、暴力、侵权、涉及违法等信息,可以点下面链接进行举报!
大家都在看
通过饲养灰鼠和白鼠(基因型未知)的实验,得到
商品满意的歇后语
用鱼缸做玄关好不好
肖旭肥龙《一路惊喜》欢乐喜剧人多少期
长安汽车蚌埠喜洋4S店在哪里啊,我有事要去这
恒邦科技园在哪里?
在?ABCD中,AC=6、BD=4,则AB的取值范围是
求一个QQ网名,要男生的,霸气一点的,不要嚣
一个人望一张图片,图片上写的是牛全身的名称
LEADTOAST地址在什么地方,想过去办事
除了耶和华谁是神呢歌谱
“春花秋月何时了,往事知多少,小楼昨夜又东风
女人吃什么可以祛斑
如何把超市搬到网上去销售呢?
函数一定能用曲线表达?曲线一定能用函数表达?
推荐资讯
美人计美容美体生活馆地址有知道的么?有点事
夫妻之间有叫爸爸妈妈的的吗
从汕头汽车总站出发到厦门的车,在厦门哪个汽
8欧0.5瓦和8欧2.5瓦喇叭通用吗
岐山擀面皮麻辣烫学院西路分店怎么去啊,有知
酸也是一种甜作文
用万用表怎么测网线
dnf谁给我好号啊?原来的号真的玩不下去了。
泰坦尼克号的吨位是不是超过当时的战列舰了
科鲁兹1.6l发动机lde发动机曲轴轴承盖的安装
避孕药最晚什么时候吃
培育能保持亲本高甜度的甜菜苗所采用的主要技
正方形一边上任一点到这个正方形两条对角线的
阴历怎么看 ?