HomeSearch

VB.NET ReDim Keyword (Array.Resize)

Use ReDim to resize an array. Benchmark ReDim against Array.Resize.

ReDim. This keyword resizes an array. We specify the maximum number of elements we want the array to have. ReDim then creates a new array of that size.ArrayKeywords

With ReDim, we specify the last index we want the array size to have. In this way it is the same as a Dim statement. ReDim can shorten or lengthen an array.

An example. Here we create an Integer array of 3 elements. We then expand the array and zero it out with ReDim. We then shrink the array with ReDim.
VB.NET program that uses ReDim Module Module1 Sub Main() ' Create an array with 3 Integer elements. Dim x() As Integer = New Integer() {1, 2, 3} Console.WriteLine(String.Join(",", x)) ' Use ReDim to resize the array. ReDim x(5) Console.WriteLine(String.Join(",", x)) ' Use ReDim to shorten the array. ReDim x(2) Console.WriteLine(String.Join(",", x)) End Sub End Module Output 1,2,3 0,0,0,0,0,0 0,0,0

Array.Resize. With Array.Resize we can resize an array, but it is not zeroed out. In this way Array.Resize is different than ReDim.
VB.NET program that uses Array.Resize Module Module1 Sub Main() Dim x() As Integer = New Integer() {1, 2, 3} ' This keeps the existing elements. Array.Resize(x, 6) Console.WriteLine(String.Join(",", x)) End Sub End Module Output 1,2,3,0,0,0

Performance, ReDim. ReDim and Array.Resize do not do the exact same thing—Array.Resize retains existing elements, but ReDim clears everything. Still we can compare the performance.

Version 1: This version uses ReDim to resize the array to have 6 elements (it specifies 5 as the last index).

Version 2: This version uses Array.Resize. It retains the existing elements, unlike ReDim.

Result: ReDim is faster than Array.Resize. So if possible, ReDim is a better option than Array.Resize.

VB.NET program that benchmarks ReDim, Array.Resize Module Module1 Sub Main() Dim m As Integer = 10000000 Dim s1 As Stopwatch = Stopwatch.StartNew ' Version 1: use ReDim. For i As Integer = 0 To m - 1 Dim x() As Integer = New Integer() {1, 2, 3} ReDim x(5) If Not x.Length = 6 Then Return End If Next s1.Stop() Dim s2 As Stopwatch = Stopwatch.StartNew ' Version 2: use Array.Resize. For i As Integer = 0 To m - 1 Dim x() As Integer = New Integer() {1, 2, 3} Array.Resize(x, 6) If Not x.Length = 6 Then Return End If Next s2.Stop() Dim u As Integer = 1000000 Console.WriteLine(((s1.Elapsed.TotalMilliseconds * u) / m).ToString("0.00 ns")) Console.WriteLine(((s2.Elapsed.TotalMilliseconds * u) / m).ToString("0.00 ns")) End Sub End Module Output 10.70 ns ReDim 70.40 ns Array.Resize

Some last comments. ReDim allocates a new array in place of an existing array. All the elements of a ReDim array are erased and set to their default.
Home
Dot Net Perls
© 2007-2020 Sam Allen. Every person is special and unique. Send bug reports to info@dotnetperls.com.