VB.NET With Statement

Use and benchmark the With keyword. This keyword will reuse a variable or expression.

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. And we further see if With has a performance advantage.

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.StringBuilder

And: Lines can begin with the dot. Also, the dot can be used in the same way in an expression or argument.

VB.NET program that uses With statement 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 Module Output 5 otNet

Benchmark. I reviewed the Microsoft page on the VB.NET With statement. One interesting assertion is that the With statement can improve performance. I was curious as to how this was possible.With Statement: Microsoft Docs

Note: Pushing an instance expression onto the evaluation stack is fast. I constructed this simple benchmark.

Loops: 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.

VB.NET program that benchmarks With 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 Module Output 805.7033 (No With) 807.155 (With)

Summary. We looked at the With statement, which saves you the effort of retyping the instance expression in a VB.NET block for several statements. The With statement seems to be syntactic sugar. It makes the program shorter or easier to read.
Dot Net Perls
© 2007-2020 Sam Allen. Every person is special and unique. Send bug reports to