In this benchmark we see how a capacity can speed up list initialization. We create many Lists in a tight loop.
Module Module1
Sub Main()
Dim m As Integer = 10000000
A()
B()
Dim s1 As Stopwatch = Stopwatch.StartNew
' Version 1: initialize list with an array argument.
For i As Integer = 0 To m - 1
A()
Next
s1.Stop()
Dim s2 As Stopwatch = Stopwatch.StartNew
' Version 2: initialize list with Add() calls.
For i As Integer = 0 To m - 1
B()
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
Sub A()
' Add with initialization statement.
Dim a As List(Of Integer) = New List(Of Integer)({400, 500, 600, 700, 800})
If Not a(0) = 400 Then
Console.WriteLine(
"X")
End If
End Sub
Sub B()
' Add with Add() calls, specify capacity.
Dim a As List(Of Integer) = New List(Of Integer)(5)
a.Add(400)
a.Add(500)
a.Add(600)
a.Add(700)
a.Add(800)
If Not a(0) = 400 Then
Console.WriteLine(
"X")
End If
End Sub
End Module
83.48 ns Initialize with one statement
20.41 ns Initialize with capacity, Add() calls