Home
Search
 
What's New
Index
Books
Links
Q & A
Newsletter
Banners
 
Feedback
Tip Jar
 
 
 
 
 
 
 
 
Old Pages
 
Old Index
Site Map
What's New
 
Books
How To
Tips & Tricks
Tutorials
Stories
Performance
Essays
Links
Q & A
New in VB6
Free Stuff
Pictures
 
 
 
TitleCompare the speeds of Choose and Select Case in VB .NET
KeywordsChoose, Select Case, VB.NET, performance
CategoriesVB.NET, Tips and Tricks, Software Engineering
 
This example repeats a loop assigning a value using Choose and Select Case to see which is faster. It also creates an array of values and uses an index into the array to assign values.

In my tests, Choose took more than 22 times as long as Select Case. Select Case took about twice as long as the array assignment.

 
Private Sub btnGo_Click(ByVal sender As System.Object, _
    ByVal e As System.EventArgs) Handles btnGo.Click
    Dim start_time As DateTime
    Dim stop_time As DateTime
    Dim num_trials As Long = Long.Parse(txtNumTrials.Text)
    Dim ellapsed_time As TimeSpan
    Dim a As Long

    lblChoose.Text = ""
    lblSelectCase.Text = ""
    Application.DoEvents()

    start_time = Now
    for i as integer  = 1 to num_trials
        a = Choose(1 + i Mod 10, 1, 2, 3, 4, 5, 6, 7, 8, 9, _
            10)
    Next i
    stop_time = Now
    ellapsed_time = stop_time.Subtract(start_time)
    lblChoose.Text = _
        ellapsed_time.TotalSeconds().ToString("0.00") & " " & _
        "seconds"

    start_time = Now
    For i As Integer = 1 To num_trials
        Select Case 1 + i Mod 10
            Case 1
                a = 1
            Case 2
                a = 2
            Case 3
                a = 3
            Case 4
                a = 4
            Case 5
                a = 5
            Case 6
                a = 6
            Case 7
                a = 7
            Case 8
                a = 8
            Case 9
                a = 9
            Case 10
                a = 10
        End Select
    Next i
    stop_time = Now
    ellapsed_time = stop_time.Subtract(start_time)
    lblSelectCase.Text = _
        ellapsed_time.TotalSeconds().ToString("0.00") & " " & _
        "seconds"

    Dim values() As Long = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}
    start_time = Now
    For i As Integer = 1 To num_trials
        a = values(i Mod 10)
    Next i
    stop_time = Now
    ellapsed_time = stop_time.Subtract(start_time)
    lblArray.Text = _
        ellapsed_time.TotalSeconds().ToString("0.00") & " " & _
        "seconds"
End Sub
 
 
Copyright © 1997-2003 Rocky Mountain Computer Consulting, Inc.   All rights reserved.
  Updated