With. 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.
Syntax and performance. We see if With has a performance advantage with a benchmark. We also analyze its syntax for clarity. Is it worth using?
Example. 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.
Then You can omit the variable name in subsequent statements. This can reduce the amount of typing you have to do.
And Lines can begin with the dot. Also, the dot can be used in the same way in an expression or argument.
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
otNet
Benchmark. I reviewed the Microsoft page on the VB.NET With statement. One interesting assertion is that the With statement can improve performance.
Note Pushing an instance expression onto the evaluation stack is fast. I constructed this simple benchmark.
Detail You can see that the inner loops clear the List instance and add 5 elements to it on every iteration.
And The second loop uses the With statement. I was unable to find any performance advantage from the With statement.
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)
Summary. 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.
Dot Net Perls is a collection of tested code examples. Pages are continually updated to stay current, with code correctness a top priority.
Sam Allen is passionate about computer languages. In the past, his work has been recommended by Apple and Microsoft and he has studied computers at a selective university in the United States.
This page was last updated on Apr 13, 2022 (edit link).