Fastest way to add an Item to an Array
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 SubEnd Module
Usage:
Dim arr As Integer() = {1, 2, 3}Dim newItem As Integer = 4arr.Add(newItem)' --> duration for adding 100.000 items: 1 msec' --> duration for adding 100.000.000 items: 1168 msec
Dim arr As Integer() = {1, 2, 3}Dim newItem As Integer = 4ReDim Preserve arr (3)arr(3)=newItem
for more info Redim
For those who didn't know what next, just add new module file and put @jor code (with my little hacked, supporting 'nothing' array) below.
Module ArrayExtension <Extension()> _ Public Sub Add(Of T)(ByRef arr As T(), item As T) If arr IsNot Nothing Then Array.Resize(arr, arr.Length + 1) arr(arr.Length - 1) = item Else ReDim arr(0) arr(0) = item End If End SubEnd Module