使用数组或列表哪个更好? [英] Which is better to use array or List<>?
问题描述
我想知道哪种类型会具有更好的性能以及您认为应该使用哪种类型.
I was wondering which type would have better performance and which you think should be used.
例如,我有一个字符串列表,不知道我需要多少项,因此使用 .Add(String) 函数非常方便.我可以随时轻松地将新字符串添加到列表中.
For example I have a List of strings not knowing how many items I will need so having the .Add(String) function is really convenient. I can Add new strings to the list at any time easily.
使用每种方法的优点/缺点是什么?
What are the advantages/disadvantages of using each?
列表是新数组吗?
推荐答案
正确回答问题确实需要更多上下文:
More context is really required to answer the question properly:
在公共 API 中,您应该尝试使用抽象集合类型,以便您以后可以根据需要更改内部实现.
In a public API, you should try to use abstract collection types, so that you can change the internal implementation later if you need to.
- 如果集合不应该被外界改变,使用
IEnumerable
. - 如果集合将被外界改变,请使用
ICollection
. - 如果需要索引访问,请使用
IList
.
- If the collection should not be changed by the outside world, use
IEnumerable<T>
. - If the collection will be changed by the outside world, use
ICollection<T>
. - If indexed access is required, use
IList<T>
.
在私有实现中,使用抽象类型并不重要:
In a private implementation, it's not as important to use the abstract types:
- 如果您需要索引访问并知道最终大小,请使用
T[]
或List
. - 如果您需要索引访问并且不知道最终大小,请使用
List
. - 如果您打算访问 LIFO 模式中的元素,请使用
Stack
. - 如果您计划访问 FIFO 模式中的元素,请使用
Queue
. - 如果您需要访问列表开头和结尾的元素,而不是中间的元素,请使用
LinkedList
. - 如果您不想重复,请使用
HashSet
.
- If you need indexed access and know the final size, use
T[]
orList<T>
. - If you need indexed access and don't know the final size, use
List<T>
. - If you plan to access elements in a LIFO pattern, use
Stack<T>
. - If you plan to access elements in a FIFO pattern, use
Queue<T>
. - If you need to access elements at the beginning and end of the list, but not in the middle, use
LinkedList<T>
. - If you don't want duplicates, use
HashSet<T>
.
在 .NET 4.0 中,您有更多选择,但这些是基础.
In .NET 4.0 you have a few more choices, but those are the basics.
这篇关于使用数组或列表哪个更好?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!