首先应该理解数组在《数据结构》中的概念,数组是一个线性表,在定义的时候由内存分配一个指定大小的内存空间,所以相较于链表(C#中又叫集合)缺点就是不利于扩展。
针对合并两个数组的方法就是创建一个新的数组(大于两个数组的大小之和)来存放两个数组,在没有用到Array.Copy()这个又C#程序集提供的方法时,我们只能将数组中元素一个一个依次放入新数组中,如下所示
/// <summary>
/// 将数组a,b进行合并
/// </summary>
/// <param name="a"></param>
/// <param name="b"></param>
/// <param name="c"></param>
private static byte[] Combine(byte[] a, byte[] b)
{
byte[] c = new byte[a.Length + b.Length];
for (int i = 0; i < a.Length; i++)
{
c[i] = a[i];
}
for (int j = a.Length; j < a.Length+ b.Length; j++)
{
c[j] = b[j];
}
return c;
}
这个方法写法上没什么问题,但有一个严重的问题,在数据量较大的时候,相较于Array.Copy效率极低
同时也不如Array.Copy()一行代码来的简洁。如下所示
/// <summary>
/// 将数组a,b进行合并
/// </summary>
/// <param name="a"></param>
/// <param name="b"></param>
/// <param name="c"></param>
private static byte[] Combine2(byte[] a, byte[] b)
{
byte[] c = new byte[a.Length + b.Length];
Array.Copy(a, 0, c, 0, a.Length);
Array.Copy(b, 0, c, a.Length, b.Length);
return c;
}
效率比较
1将两个长度为50000的数组进行合并
using System;
using System.Collections.Generic;
using System.Text;
namespace ArrayCopyTest
{
class Program
{
static void Main(string[] args)
{
//使用两个长度为50000的数组
byte[] a = new byte[50000];
byte[] b = new byte[50000];
#region 对a,b进行随机赋值
Random random = new Random();
for (int i = 0; i < a.Length; i++)
{
a[i] = (byte)random.Next(0, 255);
}
for (int i = 0; i < b.Length; i++)
{
b[i] = (byte)random.Next(0, 255);
}
#endregion
Console.WriteLine("开始记录时间");
DateTime beforDT = DateTime.Now;//记录开始时间
byte[] c1 = Combine1(a, b);
DateTime afterDT = DateTime.Now;//记录结束时间
TimeSpan ts = afterDT.Subtract(beforDT); //时间差
Console.WriteLine("Combine1总共花费{0}ms.", ts.TotalMilliseconds);
Console.WriteLine("开始记录时间");
DateTime beforDT2 = DateTime.Now;//记录开始时间
byte[] c2 = Combine2(a, b);
DateTime afterDT2 = DateTime.Now;//记录结束时间
TimeSpan ts2 = afterDT2.Subtract(beforDT2); //时间差
Console.WriteLine("Combine2总共花费{0}ms.", ts2.TotalMilliseconds);
Console.ReadKey();
}
/// <summary>
/// 将数组a,b进行合并
/// </summary>
/// <param name="a"></param>
/// <param name="b"></param>
/// <param name="c"></param>
private static byte[] Combine1(byte[] a, byte[] b)
{
byte[] c = new byte[a.Length + b.Length];
for (int i = 0; i < a.Length; i++)
{
c[i] = a[i];
}
for (int j = a.Length; j < a.Length + b.Length; j++)
{
c[j] = b[j-a.Length];
}
return c;
}
/// <summary>
/// 将数组a,b进行合并
/// </summary>
/// <param name="a"></param>
/// <param name="b"></param>
/// <param name="c"></param>
private static byte[] Combine2(byte[] a, byte[] b)
{
byte[] c = new byte[a.Length + b.Length];
Array.Copy(a, 0, c, 0, a.Length);
Array.Copy(b, 0, c, a.Length, b.Length);
return c;
}
}
}
数组长度改为5000000,花费时间更加明显