将项目添加到数组的最快方法 [英] Fastest way to add an Item to an Array
问题描述
将新项目添加到现有数组的最快方法是什么?
What is the fastest way to add a new item to an existing array?
Dim arr As Integer() = {1, 2, 3}
Dim newItem As Integer = 4
(我已经知道在处理动态项目列表时,您应该使用 List
、ArrayList
或类似的 IEnumerables
.但是什么如果您坚持使用数组的遗留代码,该怎么办?)
(I already know that when working with dynamic list of items you should rather use a List
, ArrayList
or similar IEnumerables
. But what to do if you're stuck to legacy code that uses arrays?)
到目前为止我尝试过的:
What I've tried so far:
' A) converting to List, add item and convert back
Dim list As List(Of Integer)(arr)
list.Add(newItem)
arr = list.ToArray()
' --> duration for adding 100.000 items: 33270 msec
' B) redim array and add item
ReDim Preserve arr(arr.Length)
arr(arr.Length - 1) = newItem
' --> duration for adding 100.000 items: 9237 msec
' C) using Array.Resize
Array.Resize(arr, arr.Length + 1)
arr(arr.Length - 1) = newItem
' --> duration for adding 100.000 items: 1 msec
' --> duration for adding 100.000.000 items: 1168 msec
A) 看起来很慢,因为每次添加一个项目时,都会对整个数组进行两次转换.B) 看起来更快,但在 ReDim Preserve
期间仍然复制了一次数组.C) 在这一点上似乎是最快的.有没有更好的?
A) seems very slow since every time an item is added two conversions of the whole array are done. B) seems faster but still the array is copied once during the ReDim Preserve
. C) seems to be the fastest at this point. Is there anything better?
推荐答案
Case C) 是最快的.将此作为扩展名:
Case C) is the fastest. Having this as an extension:
Public Module MyExtensions
<Extension()> _
Public Sub Add(Of T)(ByRef arr As T(), item As T)
Array.Resize(arr, arr.Length + 1)
arr(arr.Length - 1) = item
End Sub
End Module
用法:
Dim arr As Integer() = {1, 2, 3}
Dim newItem As Integer = 4
arr.Add(newItem)
' --> duration for adding 100.000 items: 1 msec
' --> duration for adding 100.000.000 items: 1168 msec
这篇关于将项目添加到数组的最快方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!