MyClass[] array;
List<MyClass> list;
What are the scenarios when one is preferable over the other? And why?
当一个人比另一个更好的时候,情况是怎样的?,为什么?
14 个解决方案
#1
443
It is rare, in reality, that you would want to use an array. Definitely use a List<T>
any time you want to add/remove data, since resizing arrays is expensive. If you know the data is fixed length, and you want to micro-optimise for some very specific reason (after benchmarking), then an array may be useful.
实际上,您希望使用数组是很少见的。当你想要添加/删除数据时,一定要使用List
List<T>
offers a lot more functionality than an array (although LINQ evens it up a bit), and is almost always the right choice. Except for params
arguments, of course. ;-p
List
As a counter - List<T>
is one-dimensional; where-as you have have rectangular (etc) arrays like int[,]
or string[,,]
- but there are other ways of modelling such data (if you need) in an object model.
作为计数器列表
See also:
参见:
- How/When to abandon the use of Arrays in c#.net?
- 如何/何时放弃在c#.net中使用数组?
- Arrays, What's the point?
- 数组,有什么意义?
That said, I make a lot of use of arrays in my protobuf-net project; entirely for performance:
也就是说,我在我的原始网络项目中使用了很多数组;完全的性能:
- it does a lot of bit-shifting, so a
byte[]
is pretty much essential for encoding; - 它有很多位移位,所以一个字节[]对于编码来说非常重要;
- I use a local rolling
byte[]
buffer which I fill before sending down to the underlying stream (and v.v.); quicker thanBufferedStream
etc; - 我使用一个本地滚动字节[]缓冲区,在发送到底层流(和vv)之前,我先填充它。比BufferedStream等;
- it internally uses an array-based model of objects (
Foo[]
rather thanList<Foo>
), since the size is fixed once built, and needs to be very fast. -
它内部使用基于数组的对象模型(Foo[]而不是List
),因为它的大小是固定的,并且需要非常快。
But this is definitely an exception; for general line-of-business processing, a List<T>
wins every time.
但这绝对是个例外;对于一般的业务线处理,每次都有一个列表
#2
103
Really just answering to add a link which I'm surprised hasn't been mentioned yet: Eric's Lippert's blog entry on "Arrays considered somewhat harmful."
实际上,仅仅是添加一个我感到惊讶的链接还没有被提及:Eric的Lippert的博客条目“被认为是有害的”。
You can judge from the title that it's suggesting using collections wherever practical - but as Marc rightly points out, there are plenty of places where an array really is the only practical solution.
您可以从标题中判断,它建议使用集合,无论实际情况是什么——但正如Marc所指出的,有很多地方,数组确实是唯一可行的解决方案。
#3
39
Use an array when you are dealing with data that is:
在处理数据时使用数组:
- fixed in size, or unlikely to grow much
- 固定大小,或不太可能长得多。
- suitably large (more than 10, 50, 100 elements, depending on the algorithm)
- 适当大(超过10、50、100个元素,取决于算法)
- you will be doing lots of indexing into it, i.e. you know you will often want the third element, or the fifth, or whatever.
- 你会做很多索引,比如你会经常想要第三个元素,或者第五个元素,或者别的什么。
Use a list for:
使用列表:
- variable length data lists
- 可变长度的数据列表
- that are mostly used as a stack or a queue or need to be iterated in its entirety
- 它主要用作堆栈或队列,或者需要遍历整个队列。
- when you do not want to write an expression to derive the ultimate array size for the declaration and you do not want to wastefully pick a large number
- 当您不希望编写表达式来派生声明的最终数组大小时,您不希望浪费大量的选择。
Use a hashmap for:
使用hashmap:
- variable length data lists
- 可变长度的数据列表
- that need to be indexed like an array would
- 需要像数组一样进行索引。
In reality, you'll want a list or hashmap almost all of the time. Next time you pick a data structure, think about what it must do well for you (or your code, anyway). Then pick something based on that. When in doubt, pick something as general as possible, i.e. an interface you can replace the implementation of quite easily. Some good links in the other answers as well.
实际上,您几乎所有的时间都需要一个列表或hashmap。下次当你选择一个数据结构时,考虑一下它对你(或者你的代码)必须做的很好。然后根据这个选择一些东西。当有疑问时,选择一些尽可能通用的东西,即一个可以很容易替换实现的接口。其他答案中也有一些很好的链接。
#4
17
Notwithstanding the other answers recommending List<T>
, you'll want to use arrays when handling:
尽管有其他的推荐列表
- image bitmap data
- 图像的位图数据
- other low-level data-structures (i.e. network protocols)
- 其他低级数据结构(即网络协议)
#5
9
Unless you are really concerned with performance, and by that I mean, "Why are you using .Net instead of C++?" you should stick with List<>. It's easier to maintain and does all the dirty work of resizing an array behind the scenes for you. (If necessary, List<> is pretty smart about choosing array sizes so it doesn't need to usually.)
除非你真的关心性能,我的意思是,“你为什么用。net而不是c++ ?”你应该坚持列表<>。它更容易维护和完成所有的脏工作,在幕后为您调整数组。(如果有必要,List<>在选择数组大小时非常聪明,所以它通常不需要这样做。)
#6
5
Arrays should be used in preference to List when the immutability of the collection itself is part of the contract between the client & provider code (not necessarily immutability of the items within the collection) AND when IEnumerable is not suitable.
当集合本身的不变性是客户端和提供者代码之间的契约的一部分(不一定是集合内的项目的不可变性),并且当IEnumerable不合适时,应该优先使用数组。
For example,
例如,
var str = "This is a string";
var strChars = str.ToCharArray(); // returns array
It is clear that modification of "strChars" will not mutate the original "str" object, irrespective implementation-level knowledge of "str"'s underlying type.
显然,对“strChars”的修改不会改变原来的“str”对象,而不考虑“str”的底层类型的实现级知识。
But suppose that
但假设
var str = "This is a string";
var strChars = str.ToCharList(); // returns List<char>
strChars.Insert(0, 'X');
In this case, it's not clear from that code-snippet alone if the insert method will or will not mutate the original "str" object. It requires implementation level knowledge of String to make that determination, which breaks Design by Contract approach. In the case of String, it's not a big deal, but it can be a big deal in almost every other case. Setting the List to read-only does help but results in run-time errors, not compile-time.
在这种情况下,如果插入方法不会改变原来的“str”对象,那么仅从代码片段中就不清楚。它需要字符串的实现级别的知识来确定,这就打破了契约方法的设计。在弦的情况下,这不是什么大问题,但在几乎所有其他情况下,它都是一个大问题。将列表设置为只读确实会有所帮助,但会导致运行时错误,而不是编译时。
#7
3
If I know exactly how many elements I'm going to need, say I need 5 elements and only ever 5 elements then I use an array. Otherwise I just use a List<T>.
如果我知道我需要多少个元素,比如说我需要5个元素,只有5个元素,那么我就使用一个数组。否则,我只使用List
#8
2
Most of the times, using a List
would suffice. A List
uses an internal array to handle its data, and automatically resizes the array when adding more elements to the List
than its current capacity, which makes it more easy to use than an array, where you need to know the capacity beforehand.
大多数时候,使用一个列表就足够了。列表使用一个内部数组来处理它的数据,当在列表中添加更多元素时,它会自动调整数组的大小,而不是当前的容量,这使得它比数组更容易使用,在这里您需要事先知道容量。
See http://msdn.microsoft.com/en-us/library/ms379570(v=vs.80).aspx#datastructures20_1_topic5 for more information about Lists in C# or just decompile System.Collections.Generic.List<T>
.
请参阅http://msdn.microsoft.com/en-us/library/ms379570(v=vs.80).aspx#datastructures20_1_topic5,以获得更多关于c#或仅反编译系统的列表的信息。
If you need multidimensional data (for example using a matrix or in graphics programming), you would probably go with an array
instead.
如果您需要多维数据(例如使用一个矩阵或图形编程),您可能会选择一个数组。
As always, if memory or performance is an issue, measure it! Otherwise you could be making false assumptions about the code.
像往常一样,如果内存或性能是一个问题,测量它!否则你可能会对代码做出错误的假设。
#9
1
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.
还没有提到的另一种情况是,当一个人拥有大量的项目时,每个项目都由固定的一组相互关联的独立变量组成(例如,一个点的坐标,或者一个三维三角形的顶点)。一组暴露场结构将允许其元素有效地修改“到位”——这是任何其他集合类型都不可能实现的。由于结构数组在RAM中连续地保存元素,对数组元素的顺序访问可以非常快。在需要通过数组进行多次顺序传递的情况下,一组结构可能比数组或其他类对象引用的集合的性能要好于2:1;此外,更新元素的能力可能允许一系列结构的性能超过任何其他类型的结构集合。
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< t>,但是暴露了它的支持存储,从而允许一个人表示MyPoints.Add(nextPoint);或MyPoints.Items[23]。X + = 5;。请注意,如果代码试图访问列表的末尾,后者并不一定会抛出异常,但是在概念上,用法与list
#10
0
It completely depends on the contexts in which the data structure is needed. For example, if you are creating items to be used by other functions or services using List is the perfect way to accomplish it.
它完全依赖于需要数据结构的上下文。例如,如果您正在创建用于其他功能或服务的项目,使用列表是完成它的最佳方法。
Now if you have a list of items and you just want to display them, say on a web page array is the container you need to use.
现在,如果您有一个项目列表,并且您只是想要显示它们,那么在web页面数组中显示您需要使用的容器。
#11
0
Rather than going through a comparison of the features of each data type, I think the most pragmatic answer is "the differences probably aren't that important for what you need to accomplish, especially since they both implement IEnumerable
, so follow popular convention and use a List
until you have a reason not to, at which point you probably will have your reason for using an array over a List
."
而不是通过比较每个数据类型的特点,我认为最务实的回答是“可能的差异并不重要,你需要完成什么,特别是因为他们都实现IEnumerable,跟随流行的公约和使用列表,直到你有一个理由不去,此时你可能会使用一个数组列表的理由。”
Most of the time in managed code you're going to want to favor collections being as easy to work with as possible over worrying about micro-optimizations.
在托管代码中,大多数情况下,您将希望支持集合尽可能容易地工作,而不必担心微优化。
#12
0
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.
net中的列表是数组的包装,并在内部使用数组。列表操作的时间复杂度与数组的时间复杂度相同,不过,所有添加的功能/列表的使用(比如自动调整大小和列表类的方法)都有一些额外的开销。基本上,我建议在所有情况下使用列表,除非有令人信服的理由不这样做,例如,如果您需要编写极其优化的代码,或者正在处理围绕数组构建的其他代码。
#13
0
Since no one mention: MyClass[]
and List<MyClass>
both implement IList<MyClass>
. If you are pondering which one to accept as an argument, you may declare it as IList<MyClass>
for callers' convenience. (e.g. Foo(IList<int> foo)
can be called like Foo(new[] { 1, 2, 3 })
or Foo(new List<int> { 1, 2, 3 })
)
因为没有人提到:MyClass[]和List
#14
0
They may be unpopular, but I am a fan of Arrays in game projects. - Iteration speed can be important in some cases, foreach on an Array has significantly less overhead if you are not doing much per element - Adding and removing is not that hard with helper functions - Its slower, but in cases where you only build it once it may not matter - In most cases, less extra memory is wasted (only really significant with Arrays of structs) - Slightly less garbage and pointers and pointer chasing
它们可能不受欢迎,但我喜欢在游戏项目中使用数组。——迭代速度可能是重要的在某些情况下,foreach数组上显著的开销更少,如果你不做得每个元素,添加和删除与辅助函数并不难——慢,但在这种情况下,你只能建造一次它可能并不重要,在大多数情况下,额外的内存更少浪费(只有真正重要的结构体数组)——略低于垃圾和指针和指针追逐
That being said, I use List far more often than Arrays in practice, but they each have their place.
话虽如此,我在实践中使用列表的次数远远多于数组,但它们都有各自的位置。
It would be nice if List where a built in type so that they could optimize out the wrapper and enumeration overhead.
如果列表中有一个内置类型,这样它们可以优化包装器和枚举开销,那就更好了。
#1
443
It is rare, in reality, that you would want to use an array. Definitely use a List<T>
any time you want to add/remove data, since resizing arrays is expensive. If you know the data is fixed length, and you want to micro-optimise for some very specific reason (after benchmarking), then an array may be useful.
实际上,您希望使用数组是很少见的。当你想要添加/删除数据时,一定要使用List
List<T>
offers a lot more functionality than an array (although LINQ evens it up a bit), and is almost always the right choice. Except for params
arguments, of course. ;-p
List
As a counter - List<T>
is one-dimensional; where-as you have have rectangular (etc) arrays like int[,]
or string[,,]
- but there are other ways of modelling such data (if you need) in an object model.
作为计数器列表
See also:
参见:
- How/When to abandon the use of Arrays in c#.net?
- 如何/何时放弃在c#.net中使用数组?
- Arrays, What's the point?
- 数组,有什么意义?
That said, I make a lot of use of arrays in my protobuf-net project; entirely for performance:
也就是说,我在我的原始网络项目中使用了很多数组;完全的性能:
- it does a lot of bit-shifting, so a
byte[]
is pretty much essential for encoding; - 它有很多位移位,所以一个字节[]对于编码来说非常重要;
- I use a local rolling
byte[]
buffer which I fill before sending down to the underlying stream (and v.v.); quicker thanBufferedStream
etc; - 我使用一个本地滚动字节[]缓冲区,在发送到底层流(和vv)之前,我先填充它。比BufferedStream等;
- it internally uses an array-based model of objects (
Foo[]
rather thanList<Foo>
), since the size is fixed once built, and needs to be very fast. -
它内部使用基于数组的对象模型(Foo[]而不是List
),因为它的大小是固定的,并且需要非常快。
But this is definitely an exception; for general line-of-business processing, a List<T>
wins every time.
但这绝对是个例外;对于一般的业务线处理,每次都有一个列表
#2
103
Really just answering to add a link which I'm surprised hasn't been mentioned yet: Eric's Lippert's blog entry on "Arrays considered somewhat harmful."
实际上,仅仅是添加一个我感到惊讶的链接还没有被提及:Eric的Lippert的博客条目“被认为是有害的”。
You can judge from the title that it's suggesting using collections wherever practical - but as Marc rightly points out, there are plenty of places where an array really is the only practical solution.
您可以从标题中判断,它建议使用集合,无论实际情况是什么——但正如Marc所指出的,有很多地方,数组确实是唯一可行的解决方案。
#3
39
Use an array when you are dealing with data that is:
在处理数据时使用数组:
- fixed in size, or unlikely to grow much
- 固定大小,或不太可能长得多。
- suitably large (more than 10, 50, 100 elements, depending on the algorithm)
- 适当大(超过10、50、100个元素,取决于算法)
- you will be doing lots of indexing into it, i.e. you know you will often want the third element, or the fifth, or whatever.
- 你会做很多索引,比如你会经常想要第三个元素,或者第五个元素,或者别的什么。
Use a list for:
使用列表:
- variable length data lists
- 可变长度的数据列表
- that are mostly used as a stack or a queue or need to be iterated in its entirety
- 它主要用作堆栈或队列,或者需要遍历整个队列。
- when you do not want to write an expression to derive the ultimate array size for the declaration and you do not want to wastefully pick a large number
- 当您不希望编写表达式来派生声明的最终数组大小时,您不希望浪费大量的选择。
Use a hashmap for:
使用hashmap:
- variable length data lists
- 可变长度的数据列表
- that need to be indexed like an array would
- 需要像数组一样进行索引。
In reality, you'll want a list or hashmap almost all of the time. Next time you pick a data structure, think about what it must do well for you (or your code, anyway). Then pick something based on that. When in doubt, pick something as general as possible, i.e. an interface you can replace the implementation of quite easily. Some good links in the other answers as well.
实际上,您几乎所有的时间都需要一个列表或hashmap。下次当你选择一个数据结构时,考虑一下它对你(或者你的代码)必须做的很好。然后根据这个选择一些东西。当有疑问时,选择一些尽可能通用的东西,即一个可以很容易替换实现的接口。其他答案中也有一些很好的链接。
#4
17
Notwithstanding the other answers recommending List<T>
, you'll want to use arrays when handling:
尽管有其他的推荐列表
- image bitmap data
- 图像的位图数据
- other low-level data-structures (i.e. network protocols)
- 其他低级数据结构(即网络协议)
#5
9
Unless you are really concerned with performance, and by that I mean, "Why are you using .Net instead of C++?" you should stick with List<>. It's easier to maintain and does all the dirty work of resizing an array behind the scenes for you. (If necessary, List<> is pretty smart about choosing array sizes so it doesn't need to usually.)
除非你真的关心性能,我的意思是,“你为什么用。net而不是c++ ?”你应该坚持列表<>。它更容易维护和完成所有的脏工作,在幕后为您调整数组。(如果有必要,List<>在选择数组大小时非常聪明,所以它通常不需要这样做。)
#6
5
Arrays should be used in preference to List when the immutability of the collection itself is part of the contract between the client & provider code (not necessarily immutability of the items within the collection) AND when IEnumerable is not suitable.
当集合本身的不变性是客户端和提供者代码之间的契约的一部分(不一定是集合内的项目的不可变性),并且当IEnumerable不合适时,应该优先使用数组。
For example,
例如,
var str = "This is a string";
var strChars = str.ToCharArray(); // returns array
It is clear that modification of "strChars" will not mutate the original "str" object, irrespective implementation-level knowledge of "str"'s underlying type.
显然,对“strChars”的修改不会改变原来的“str”对象,而不考虑“str”的底层类型的实现级知识。
But suppose that
但假设
var str = "This is a string";
var strChars = str.ToCharList(); // returns List<char>
strChars.Insert(0, 'X');
In this case, it's not clear from that code-snippet alone if the insert method will or will not mutate the original "str" object. It requires implementation level knowledge of String to make that determination, which breaks Design by Contract approach. In the case of String, it's not a big deal, but it can be a big deal in almost every other case. Setting the List to read-only does help but results in run-time errors, not compile-time.
在这种情况下,如果插入方法不会改变原来的“str”对象,那么仅从代码片段中就不清楚。它需要字符串的实现级别的知识来确定,这就打破了契约方法的设计。在弦的情况下,这不是什么大问题,但在几乎所有其他情况下,它都是一个大问题。将列表设置为只读确实会有所帮助,但会导致运行时错误,而不是编译时。
#7
3
If I know exactly how many elements I'm going to need, say I need 5 elements and only ever 5 elements then I use an array. Otherwise I just use a List<T>.
如果我知道我需要多少个元素,比如说我需要5个元素,只有5个元素,那么我就使用一个数组。否则,我只使用List
#8
2
Most of the times, using a List
would suffice. A List
uses an internal array to handle its data, and automatically resizes the array when adding more elements to the List
than its current capacity, which makes it more easy to use than an array, where you need to know the capacity beforehand.
大多数时候,使用一个列表就足够了。列表使用一个内部数组来处理它的数据,当在列表中添加更多元素时,它会自动调整数组的大小,而不是当前的容量,这使得它比数组更容易使用,在这里您需要事先知道容量。
See http://msdn.microsoft.com/en-us/library/ms379570(v=vs.80).aspx#datastructures20_1_topic5 for more information about Lists in C# or just decompile System.Collections.Generic.List<T>
.
请参阅http://msdn.microsoft.com/en-us/library/ms379570(v=vs.80).aspx#datastructures20_1_topic5,以获得更多关于c#或仅反编译系统的列表的信息。
If you need multidimensional data (for example using a matrix or in graphics programming), you would probably go with an array
instead.
如果您需要多维数据(例如使用一个矩阵或图形编程),您可能会选择一个数组。
As always, if memory or performance is an issue, measure it! Otherwise you could be making false assumptions about the code.
像往常一样,如果内存或性能是一个问题,测量它!否则你可能会对代码做出错误的假设。
#9
1
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.
还没有提到的另一种情况是,当一个人拥有大量的项目时,每个项目都由固定的一组相互关联的独立变量组成(例如,一个点的坐标,或者一个三维三角形的顶点)。一组暴露场结构将允许其元素有效地修改“到位”——这是任何其他集合类型都不可能实现的。由于结构数组在RAM中连续地保存元素,对数组元素的顺序访问可以非常快。在需要通过数组进行多次顺序传递的情况下,一组结构可能比数组或其他类对象引用的集合的性能要好于2:1;此外,更新元素的能力可能允许一系列结构的性能超过任何其他类型的结构集合。
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< t>,但是暴露了它的支持存储,从而允许一个人表示MyPoints.Add(nextPoint);或MyPoints.Items[23]。X + = 5;。请注意,如果代码试图访问列表的末尾,后者并不一定会抛出异常,但是在概念上,用法与list
#10
0
It completely depends on the contexts in which the data structure is needed. For example, if you are creating items to be used by other functions or services using List is the perfect way to accomplish it.
它完全依赖于需要数据结构的上下文。例如,如果您正在创建用于其他功能或服务的项目,使用列表是完成它的最佳方法。
Now if you have a list of items and you just want to display them, say on a web page array is the container you need to use.
现在,如果您有一个项目列表,并且您只是想要显示它们,那么在web页面数组中显示您需要使用的容器。
#11
0
Rather than going through a comparison of the features of each data type, I think the most pragmatic answer is "the differences probably aren't that important for what you need to accomplish, especially since they both implement IEnumerable
, so follow popular convention and use a List
until you have a reason not to, at which point you probably will have your reason for using an array over a List
."
而不是通过比较每个数据类型的特点,我认为最务实的回答是“可能的差异并不重要,你需要完成什么,特别是因为他们都实现IEnumerable,跟随流行的公约和使用列表,直到你有一个理由不去,此时你可能会使用一个数组列表的理由。”
Most of the time in managed code you're going to want to favor collections being as easy to work with as possible over worrying about micro-optimizations.
在托管代码中,大多数情况下,您将希望支持集合尽可能容易地工作,而不必担心微优化。
#12
0
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.
net中的列表是数组的包装,并在内部使用数组。列表操作的时间复杂度与数组的时间复杂度相同,不过,所有添加的功能/列表的使用(比如自动调整大小和列表类的方法)都有一些额外的开销。基本上,我建议在所有情况下使用列表,除非有令人信服的理由不这样做,例如,如果您需要编写极其优化的代码,或者正在处理围绕数组构建的其他代码。
#13
0
Since no one mention: MyClass[]
and List<MyClass>
both implement IList<MyClass>
. If you are pondering which one to accept as an argument, you may declare it as IList<MyClass>
for callers' convenience. (e.g. Foo(IList<int> foo)
can be called like Foo(new[] { 1, 2, 3 })
or Foo(new List<int> { 1, 2, 3 })
)
因为没有人提到:MyClass[]和List
#14
0
They may be unpopular, but I am a fan of Arrays in game projects. - Iteration speed can be important in some cases, foreach on an Array has significantly less overhead if you are not doing much per element - Adding and removing is not that hard with helper functions - Its slower, but in cases where you only build it once it may not matter - In most cases, less extra memory is wasted (only really significant with Arrays of structs) - Slightly less garbage and pointers and pointer chasing
它们可能不受欢迎,但我喜欢在游戏项目中使用数组。——迭代速度可能是重要的在某些情况下,foreach数组上显著的开销更少,如果你不做得每个元素,添加和删除与辅助函数并不难——慢,但在这种情况下,你只能建造一次它可能并不重要,在大多数情况下,额外的内存更少浪费(只有真正重要的结构体数组)——略低于垃圾和指针和指针追逐
That being said, I use List far more often than Arrays in practice, but they each have their place.
话虽如此,我在实践中使用列表的次数远远多于数组,但它们都有各自的位置。
It would be nice if List where a built in type so that they could optimize out the wrapper and enumeration overhead.
如果列表中有一个内置类型,这样它们可以优化包装器和枚举开销,那就更好了。