How can you use the With statement? The With statement is available for use in VB.NET programs. We use this statement in a program.
We see if With has a performance advantage with a benchmark. We also analyze its syntax for clarity. Is it worth using?
Let's begin with a simple program that uses the StringBuilder type, which provides fast appending of strings. You use the With statement on a variable name.
Imports System.Text
Module Module1
Sub Main()
Dim builder As StringBuilder = New StringBuilder()
With builder
.Append("Dot")
.Append("Net")
.Remove(0, 1)
Console.WriteLine(.Length)
Console.WriteLine(.ToString())
End With
End Sub
End Module5
otNetI reviewed the Microsoft page on the VB.NET With statement. One interesting assertion is that the With statement can improve performance.
List instance and add 5 elements to it on every iteration.Imports System.Text
Module Module1
Sub Main()
Dim list As List(Of String) = New List(Of String)(5)
Dim sw As Stopwatch = Stopwatch.StartNew
For i As Integer = 0 To 10000000
list.Clear()
list.Add("a")
list.Add("b")
list.Add("c")
list.Add("d")
list.Add("e")
Next
sw.Stop()
Dim sw2 As Stopwatch = Stopwatch.StartNew
For i As Integer = 0 To 10000000
With List
.Clear()
.Add("a")
.Add("b")
.Add("c")
.Add("d")
.Add("e")
End With
Next
sw2.Stop()
Console.WriteLine(sw.Elapsed.TotalMilliseconds)
Console.WriteLine(sw2.Elapsed.TotalMilliseconds)
End Sub
End Module805.7033 (No With)
807.155 (With)We looked at the With statement, which saves you the effort of retyping an instance expression for several statements. The With statement makes the program shorter or easier to read.