使用锯齿数组提高效率
这个范例比较多维数组和锯齿数据的性能差异
所谓锯齿数组,是一种特殊的数组,即我们常说的数组的数组。
我们所使用的范例是把一年的数据用随机数填充起来
如果用多维数组的话,因为预先定义好了维的长度,所以事实上在里面是有空的单元的。例如第二个维是31,但是有的月份可能没有31号这一天。
锯齿数组,在数组里面放的还是数组,这样每个数组的长度是可以精确控制的
经验证明:锯齿数组不仅在某些时候节省空间,而且可以比较显著地提高性能。
static void Main(string[] args)
{
int[,] multi = new int[12, 31];
Random rnd = new Random();
int[][] jagged = new int[12][];
for (int i = 0; i < 12; i++)
{
for (int m = 0; m < DateTime.DaysInMonth(DateTime.Now.Year, i + 1) - 1; m++) {
multi[i, m] = rnd.Next(100);
}
}
Console.WriteLine("开始计算多维数组于:"+DateTime.Now.ToLongTimeString());
int sum = 0;
for (int k = 0; k < 65536; k++)
{
for (int i = 0; i < 12; i++)
{
for (int m = 0; m < DateTime.DaysInMonth(DateTime.Now.Year, i + 1) - 1; m++)
{
sum += multi[i, m];
}
}
}
Console.WriteLine("结束计算多维数组于:"+DateTime.Now.ToLongTimeString()+"\n");
for (int i = 0; i < 12; i++)
{
int days = DateTime.DaysInMonth(DateTime.Now.Year, i + 1);
jagged[i] = new int[days];
for (int m = 0; m < days - 1; m++)
{
jagged[i][m] = rnd.Next(100);
}
}
sum = 0;
Console.WriteLine("开始计算锯齿数组于:"+DateTime.Now.ToLongTimeString());
for (int k = 0; k < 65536; k++)
{
for (int i = 0; i < 12; i++)
{
int days = DateTime.DaysInMonth(DateTime.Now.Year, i + 1);
for (int m = 0; m < days - 1; m++)
{
sum += jagged[i][m];
}
}
}
Console.WriteLine("结束计算锯齿数组于:"+DateTime.Now.ToLongTimeString());
Console.Read();
}
{
int[,] multi = new int[12, 31];
Random rnd = new Random();
int[][] jagged = new int[12][];
for (int i = 0; i < 12; i++)
{
for (int m = 0; m < DateTime.DaysInMonth(DateTime.Now.Year, i + 1) - 1; m++) {
multi[i, m] = rnd.Next(100);
}
}
Console.WriteLine("开始计算多维数组于:"+DateTime.Now.ToLongTimeString());
int sum = 0;
for (int k = 0; k < 65536; k++)
{
for (int i = 0; i < 12; i++)
{
for (int m = 0; m < DateTime.DaysInMonth(DateTime.Now.Year, i + 1) - 1; m++)
{
sum += multi[i, m];
}
}
}
Console.WriteLine("结束计算多维数组于:"+DateTime.Now.ToLongTimeString()+"\n");
for (int i = 0; i < 12; i++)
{
int days = DateTime.DaysInMonth(DateTime.Now.Year, i + 1);
jagged[i] = new int[days];
for (int m = 0; m < days - 1; m++)
{
jagged[i][m] = rnd.Next(100);
}
}
sum = 0;
Console.WriteLine("开始计算锯齿数组于:"+DateTime.Now.ToLongTimeString());
for (int k = 0; k < 65536; k++)
{
for (int i = 0; i < 12; i++)
{
int days = DateTime.DaysInMonth(DateTime.Now.Year, i + 1);
for (int m = 0; m < days - 1; m++)
{
sum += jagged[i][m];
}
}
}
Console.WriteLine("结束计算锯齿数组于:"+DateTime.Now.ToLongTimeString());
Console.Read();
}
结果如下,高下立判啊