MyClass[] array;
List<MyClass> list;

当一个比另一个更可取的情况是什么?,为什么?


当前回答

它们可能不受欢迎,但我是游戏项目中的数组的粉丝。 -迭代速度在某些情况下是很重要的,如果你对每个元素不做太多操作,数组上的foreach的开销就会大大减少 -添加和删除helper函数并不难 -速度比较慢,但如果你只建了一次,那就无所谓了 -在大多数情况下,更少的额外内存被浪费(只有数组结构才真正重要) -稍微少一点垃圾和指针和指针追逐

话虽如此,在实践中,我使用列表的次数远多于数组,但它们都有各自的位置。

如果List是内置类型,那么他们就可以优化包装器和枚举开销。

其他回答

数组Vs.列表是典型的可维护性Vs.性能问题。几乎所有开发人员都遵循的经验法则是,您应该兼顾两者,但当两者发生冲突时,请选择可维护性而不是性能。该规则的例外情况是当性能已经被证明是一个问题时。如果你把这个原则应用到数组Vs.列表中,你会得到这样的结果:

使用强类型列表,直到遇到性能问题。如果遇到性能问题,请决定是否使用数组对解决方案的性能更有利,而不是在维护方面对解决方案造成损害。

填充列表比填充数组更容易。对于数组,您需要知道数据的确切长度,但对于列表,数据大小可以是任何大小。你可以把一个列表转换成一个数组。

List<URLDTO> urls = new List<URLDTO>();

urls.Add(new URLDTO() {
    key = "wiki",
    url = "https://...",
});

urls.Add(new URLDTO()
{
    key = "url",
    url = "http://...",
});

urls.Add(new URLDTO()
{
    key = "dir",
    url = "https://...",
});

// convert a list into an array: URLDTO[]
return urls.ToArray();

Another situation not yet mentioned is when one will have a large number of items, each of which consists of a fixed bunch of related-but-independent variables stuck together (e.g. the coordinates of a point, or the vertices of a 3d triangle). An array of exposed-field structures will allow the its elements to be efficiently modified "in place"--something which is not possible with any other collection type. Because an array of structures holds its elements consecutively in RAM, sequential accesses to array elements can be very fast. In situations where code will need to make many sequential passes through an array, an array of structures may outperform an array or other collection of class object references by a factor of 2:1; further, the ability to update elements in place may allow an array of structures to outperform any other kind of collection of structures.

Although arrays are not resizable, it is not difficult to have code store an array reference along with the number of elements that are in use, and replace the array with a larger one as required. Alternatively, one could easily write code for a type which behaved much like a List<T> but exposed its backing store, thus allowing one to say either MyPoints.Add(nextPoint); or MyPoints.Items[23].X += 5;. Note that the latter would not necessarily throw an exception if code tried to access beyond the end of the list, but usage would otherwise be conceptually quite similar to List<T>.

大多数情况下,使用List就足够了。List使用内部数组来处理其数据,并在向List中添加比当前容量更多的元素时自动调整数组的大小,这使得它比需要事先知道容量的数组更容易使用。

有关c#中的列表的更多信息,请参阅http://msdn.microsoft.com/en-us/library/ms379570(v=vs.80).aspx#datastructures20_1_topic5,或者只是反编译System.Collections.Generic.List<T>。

如果需要多维数据(例如使用矩阵或图形编程),则可能使用数组。

像往常一样,如果内存或性能是一个问题,测量它!否则,您可能会对代码做出错误的假设。

尽管其他答案推荐List<T>,但在处理以下问题时,您将希望使用数组:

图像位图数据 其他底层数据结构(如网络协议)