什么是多维数组和数组在C#中的数组之间的区别是什么? [英] What are the differences between a multidimensional array and an array of arrays in C#?

查看:153
本文介绍了什么是多维数组和数组在C#中的数组之间的区别是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

什么是多维数组之间的差异双击[,] 和阵列的阵列双击[] [] 在C#?

What are the differences between multidimensional arrays double[,] and array-of-arrays double[][] in C#?

如果是有区别的,什么是每个人尽其用?

If there is a difference, what is the best use for each one?

推荐答案

阵列(交错数组)的数组比多维数组更快,可以更有效地使用。多维数组有更好的语法。

Array of arrays (jagged arrays) are faster than multi-dimensional arrays and can be used more effectively. Multidimensional arrays have nicer syntax.

如果您在使用锯齿和多维数组写一些简单的code,然后用IL反汇编器检查编译的程序集,你会看到,从锯齿状(或一维)阵列的存储和检索简单IL指令而同多维数组操作方法调用它总是慢。

If you write some simple code using jagged and multidimensional arrays and then inspect the compiled assembly with an IL disassembler you will see that the storage and retrieval from jagged (or single dimensional) arrays are simple IL instructions while the same operations for multidimensional arrays are method invocations which are always slower.

考虑以下方法:

static void SetElementAt(int[][] array, int i, int j, int value)
{
    array[i][j] = value;
}

static void SetElementAt(int[,] array, int i, int j, int value)
{
    array[i, j] = value;
}

他们的IL将以下内容:

Their IL will be the following:

.method private hidebysig static void  SetElementAt(int32[][] 'array',
                                                    int32 i,
                                                    int32 j,
                                                    int32 'value') cil managed
{
  // Code size       7 (0x7)
  .maxstack  8
  IL_0000:  ldarg.0
  IL_0001:  ldarg.1
  IL_0002:  ldelem.ref
  IL_0003:  ldarg.2
  IL_0004:  ldarg.3
  IL_0005:  stelem.i4
  IL_0006:  ret
} // end of method Program::SetElementAt

.method private hidebysig static void  SetElementAt(int32[0...,0...] 'array',
                                                    int32 i,
                                                    int32 j,
                                                    int32 'value') cil managed
{
  // Code size       10 (0xa)
  .maxstack  8
  IL_0000:  ldarg.0
  IL_0001:  ldarg.1
  IL_0002:  ldarg.2
  IL_0003:  ldarg.3
  IL_0004:  call       instance void int32[0...,0...]::Set(int32,
                                                           int32,
                                                           int32)
  IL_0009:  ret
} // end of method Program::SetElementAt

在使用交错数组,你可以很容易地执行诸如排掉期和行调整大小。也许在某些情况下,多维数组的使用将更加安全,但即使微软的FxCop告诉,当你用它来分析你的项目交错数组应该用来代替多维的。

When using jagged arrays you can easily perform such operations as row swap and row resize. Maybe in some cases usage of multidimensional arrays will be more safe, but even Microsoft FxCop tells that jagged arrays should be used instead of multidimensional when you use it to analyse your projects.

这篇关于什么是多维数组和数组在C#中的数组之间的区别是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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