gpt4 book ai didi

c# - 通过索引更新 List 中的元素是否应该比使用 ArrayList 索引更快?

转载 作者:太空宇宙 更新时间:2023-11-03 20:43:51 25 4
gpt4 key购买 nike

我正在运行一些关于使用 ArrayLists 和 List 的测试。

速度在我的应用中非常重要。

我已经测试过在每个记录中创建 10000 条记录,通过索引找到一个项目然后更新该对象,例如:

List[i] = newX;

使用 arraylist 似乎更快。对吗?

更新:

使用 List[i] 方法,对于我的 List<T>方法我正在使用 LINQ 查找索引 eg/

....

int index = base.FindIndex(x=>x.AlpaNumericString = "PopItem");
base[index] = UpdatedItem;

肯定比

ArrayList.IndexOf("PopItem"))
base[index] = UpdatedItem;

最佳答案

通用列表 (List<T>) 应该总是比 ArrayList 更快。

首先,一个 ArrayList不是强类型的,接受类型 object ,所以如果你在 ArrayList 中存储值类型,它们将是 boxed and unboxed每次添加或访问它们时。

通用列表可以定义为只接受(比如)int因此,在添加/访问列表元素时不需要装箱或拆箱。

如果你正在处理引用类型,你可能仍然使用通用列表而不是 ArrayList 更好,因为尽管没有装箱/拆箱,你的通用列表是类型安全的,并且不会有从 ArrayList 的“集合”object 中检索强类型对象时需要隐式(或显式)转换类型。

可能存在一些 ArrayList 比通用列表执行得更快的边缘情况,但是,我(个人)还没有遇到过这种情况。即使是 MSDN documentation状态:

Performance Considerations

In deciding whether to use the List<(Of <(T>)>) or ArrayList class, both of which have similar functionality, remember that the List<(Of <(T>)>) class performs better in most cases and is type safe. If a reference type is used for type T of the List<(Of <(T>)>) class, the behavior of the two classes is identical. However, if a value type is used for type T, you need to consider implementation and boxing issues.

If a value type is used for type T, the compiler generates an implementation of the List<(Of <(T>)>) class specifically for that value type. That means a list element of a List<(Of <(T>)>) object does not have to be boxed before the element can be used, and after about 500 list elements are created the memory saved not boxing list elements is greater than the memory used to generate the class implementation.

Make certain the value type used for type T implements the IEquatable<(Of <(T>)>) generic interface. If not, methods such as Contains must call the Object..::.Equals(Object) method, which boxes the affected list element. If the value type implements the IComparable interface and you own the source code, also implement the IComparable<(Of <(T>)>) generic interface to prevent the BinarySearch and Sort methods from boxing list elements. If you do not own the source code, pass an IComparer<(Of <(T>)>) object to the BinarySearch and Sort methods

此外,我特别喜欢该段的最后一部分,其中指出:

It is to your advantage to use the type-specific implementation of the List<(Of <(T>)>) class instead of using the ArrayList class or writing a strongly typed wrapper collection yourself. The reason is your implementation must do what the .NET Framework does for you already, and the common language runtime can share Microsoft intermediate language code and metadata, which your implementation cannot.

触摸! :)

关于c# - 通过索引更新 List<T> 中的元素是否应该比使用 ArrayList 索引更快?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1555057/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com