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

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

问题描述

C#中多维数组double[,]和数组数组double[][]有什么区别?

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.

如果您使用锯齿形和多维数组编写一些简单的代码,然后使用 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 如下:

.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

使用锯齿状数组时,您可以轻松地执行诸如行交换和行调整大小之类的操作.也许在某些情况下使用多维数组会更安全,但即使是 Microsoft 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天全站免登陆