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

(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) 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?

Answers


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

Usage:

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

Need Your Help

Monad transformer for NonEmptyList?

scala monads scalaz monad-transformers

It seems to me that Scalaz' NonEmptyList has a monad instance, so a monad transformer for it (a bit similar to ListT) should be possible. Is that correct?

Downloading from audio html5 tags

javascript html5 audio tags html

In HTML5, is there a way to download the current song in an audio tag? I am feeding it an octet stream that it is playing, but the user cannot directly download the song from the link. Is there a w...

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.