Time different methods for testing whether a string

Started by nandagopal, Nov 10, 2008, 07:01 PM

Previous topic - Next topic

nandagopal

The program tests these methods:

    If Len(txt) = 0 Then ...
    If txt = vbNullString Then ...
    If txt = "" Then ...
    If txt = blank Then ...
    If LenB(txt) = 0 Then ...

LenB(txt) seems to be fastest with Len(txt) a very close second.

The difference between the slowest and fastest is so small, however, that it is not worth worrying about. You should use whichever method makes the code easiest to understand.


Private Sub cmdGo_Click()
Dim start_time As Single
Dim stop_time As Single
Dim num_trials As Long
Dim trial As Long
Dim i As Long
Dim txt As String
Dim blank As String

    blank = ""

    lblLen.Caption = ""
    lblNull.Caption = ""
    lblEmptyQuotes.Caption = ""
    lblBlank.Caption = ""
    lblLenB.Caption = ""
    MousePointer = vbHourglass
    num_trials = CLng(txtTrials.Text)
    DoEvents

    If chkLen.Value = vbChecked Then
        i = 0
        start_time = Timer
        For trial = 1 To num_trials
            If Len(txt) = 0 Then i = i + 1
        Next trial
        stop_time = Timer
        lblLen.Caption = Format$(stop_time - start_time, _
            "0.00")
        DoEvents
    End If

    If chkNull.Value = vbChecked Then
        i = 0
        start_time = Timer
        For trial = 1 To num_trials
            If txt = vbNullString Then i = i + 1
        Next trial
        stop_time = Timer
        lblNull.Caption = Format$(stop_time - start_time, _
            "0.00")
        DoEvents
    End If

    If chkEmptyQuotes.Value = vbChecked Then
        i = 0
        start_time = Timer
        For trial = 1 To num_trials
            If txt = "" Then i = i + 1
        Next trial
        stop_time = Timer
        lblEmptyQuotes.Caption = Format$(stop_time - _
            start_time, "0.00")
        DoEvents
    End If

    If chkBlank.Value = vbChecked Then
        i = 0
        start_time = Timer
        For trial = 1 To num_trials
            If txt = blank Then i = i + 1
        Next trial
        stop_time = Timer
        lblBlank.Caption = Format$(stop_time - start_time, _
            "0.00")
        DoEvents
    End If

    If chkLenB.Value = vbChecked Then
        i = 0
        start_time = Timer
        For trial = 1 To num_trials
            If LenB(txt) = 0 Then i = i + 1
        Next trial
        stop_time = Timer
        lblLenB.Caption = Format$(stop_time - start_time, _
            "0.00")
        DoEvents
    End If

    MousePointer = vbDefault
End Sub