MyClass[] array;
List<MyClass> list;

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


当前回答

与其对每种数据类型的特性进行比较,我认为最实用的答案是“对于您需要完成的任务来说,差异可能并不那么重要,特别是因为它们都实现了IEnumerable,所以遵循流行的惯例,使用List,直到您有理由不使用List,此时您可能会有理由使用数组而不是List。”

大多数情况下,在托管代码中,您会希望集合尽可能易于使用,而不是担心微观优化。

其他回答

Lists in .NET are wrappers over arrays, and use an array internally. The time complexity of operations on lists is the same as would be with arrays, however there is a little more overhead with all the added functionality / ease of use of lists (such as automatic resizing and the methods that come with the list class). Pretty much, I would recommend using lists in all cases unless there is a compelling reason not to do so, such as if you need to write extremely optimized code, or are working with other code that is built around arrays.

请记住,使用List是不可能做到这一点的:

List<string> arr = new List<string>();

arr.Add("string a");
arr.Add("string b");
arr.Add("string c");
arr.Add("string d");

arr[10] = "new string";

它生成一个异常。

相反,使用数组:

string[] strArr = new string[20];

strArr[0] = "string a";
strArr[1] = "string b";
strArr[2] = "string c";
strArr[3] = "string d";

strArr[10] = "new string";

但是对于数组,不会自动调整数据结构的大小。您必须手动或使用Array管理它。调整方法。

一个技巧是用一个空数组初始化List。

List<string> arr = new List<string>(new string[100]);

arr[10] = "new string";

但在这种情况下,如果你使用Add方法添加一个新元素,它将被注入到列表的末尾。

List<string> arr = new List<string>(new string[100]);

arr[10] = "new string";

arr.Add("bla bla bla"); // this will be in the end of List

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

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

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

与其对每种数据类型的特性进行比较,我认为最实用的答案是“对于您需要完成的任务来说,差异可能并不那么重要,特别是因为它们都实现了IEnumerable,所以遵循流行的惯例,使用List,直到您有理由不使用List,此时您可能会有理由使用数组而不是List。”

大多数情况下,在托管代码中,您会希望集合尽可能易于使用,而不是担心微观优化。

实际上,我只是想添加一个链接,我很惊讶还没有提到:Eric的Lippert的博客条目“数组被认为有点有害”。

您可以从标题中判断,它建议在任何可行的地方使用集合——但正如Marc正确地指出的那样,在很多地方,数组确实是唯一可行的解决方案。