使用数组或列表哪个更好? [英] Which is better to use array or List<>?

查看:25
本文介绍了使用数组或列表哪个更好?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道哪种类型会具有更好的性能以及您认为应该使用哪种类型.

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[] or List<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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆