Benchmark. A benchmark tells us a method's performance. By using For-loops with a Stopwatch, we time millions of calls—and then compute the total number of nanoseconds per call.
It is useful to learn more about VB.NET performance. Every program we write will show the benefits of this knowledge. We benchmark VB.NET subs.
Example. First we use the Stopwatch.StartNew function around each For-loop. The For-loops here execute the subs A and B a total of ten million times each.
Tip If you are timing a slower subroutine, you can adjust that total down. This also depends on your processor's speed.
Module Module1
Sub Main()
Dim m As Integer = 10000000
Dim s1 As Stopwatch = Stopwatch.StartNew
For i As Integer = 0 To m - 1
A()
Next
s1.Stop()
Dim s2 As Stopwatch = Stopwatch.StartNew
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()
Dim a As Integer = Integer.Parse("0")
End Sub
Sub B()
Dim b As Integer = Integer.Parse("0") + Integer.Parse("0")
End Sub
End Module112.22 ns
224.98 ns
Notes, program. We compute the average number of nanoseconds per function call. We multiply the milliseconds by one million to convert to total nanoseconds.
Then We divide by the number of subroutine invocations to get the average nanoseconds.
Note Please remove the method bodies of A() and B(). The Integer.Parse calls are there to demonstrate how the benchmark harness is used.
And Each Integer.Parse call happens to require 112 nanoseconds, but this is not important to know.
A review. In most cases, benchmarks of the C# language and the VB.NET language will yield identical results. But some constructs are only available in one language.
For example, the VB.NET With statement is not available in the C# language. In these situations a VB.NET benchmarking harness is useful. It improves our understanding of the language.
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 Nov 11, 2023 (edit).