VB.NET Benchmark

Use a benchmark to determine the average time required for a single Function call.

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.For Each, For

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

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.Stopwatch
Tip: If you are timing a slower subroutine, you can adjust that total down. This also depends on your processor's speed.
VB.NET program that benchmarks Subs 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 Module Output 112.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.WithDateTime

© 2007-2020 Sam Allen. Send bug reports to info@dotnetperls.com.