For some protocol testing I need to randomize the case of each character in a lot of strings. The strings are commands, created by my application, which will be sent via a winsock control to a client.
As it involves a lot of strings I want each part to be as fast as possible.
Right now I have:
Private Function RandomCaps(strText As String) As String
Dim lngChar As Long
Dim strLower As String, strUpper As String
Dim strRandom As String
strRandom = ""
strLower = LCase$(strText)
strUpper = UCase$(strText)
For lngChar = 1 To Len(strText)
If Int(2 * Rnd) = 0 Then
strRandom = strRandom & Mid$(strLower, lngChar, 1)
Else
strRandom = strRandom & Mid$(strUpper, lngChar, 1)
End If
Next lngChar
RandomCaps = strRandom
End Function
This is pretty straightforward, but probably not the fastest way.
What could I do to improve its speed?
Instead of concatenating strings together, use Mid to change the string in-place:
Private Function RandomCaps(s As String) As String
Dim uc As String
Dim i As Long
RandomCaps = LCase$(s)
uc = UCase$(s)
For i = 1 To Len(s)
If Rnd < 0.5 Then
Mid(RandomCaps, i, 1) = Mid(uc, i, 1)
End If
Next i
End Function
You can try using MidB, but it hardly makes any difference – and since it works with individual bytes, you're in for some nasty surprises if you don't know how VB6 stores strings.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With