Login | Register   
LinkedIn
Google+
Twitter
RSS Feed
Download our iPhone app
TODAY'S HEADLINES  |   ARTICLE ARCHIVE  |   FORUMS  |   TIP BANK
Browse DevX
Sign up for e-mail newsletters from DevX


Tip of the Day
Language: Visual Basic
Expertise: Intermediate
Aug 26, 1999

Speed up String Operations

It's often faster to perform string operations with byte arrays than with 32-bit VB's native double-byte character strings. Even when using 16-bit VB4's single-byte character strings, it's still often faster to convert to byte arrays before intense processing. Compare the speed at which these two procedures execute and you'll be amazed. Paste this code into the default form of a new project to see the difference:

 
Private Sub Form_Click()
	Dim s As String
	Dim i As Integer
	s = String$(50000, "1")
	Debug.Print Time
	For i = 1 To 100
		Call countCharString(s, Asc("1"))
	Next
	Debug.Print Time
	For i = 1 To 100
		Call countCharByte(s, Asc("1"))
	Next
	Debug.Print Time
End Sub

Function countCharString(s As String, _
	charASCIIValue As Integer) As Long
	Dim i As Long
	For i = 1 To Len(s)
		If Asc(Mid$(s, i, 1)) = charASCIIValue Then
			countCharString = countCharString + 1
		End If
	Next
End Function

Function countCharByte(s As String, _
	charASCIIValue As Integer) As Long
	Dim b() As Byte
	Dim i As Long
	#If Win32 Then
		b = StrConv(s, vbFromUnicode)
	#Else
		b = s
	#End If

	For i = 0 To UBound(b)
		If b(i) = charASCIIValue Then
			countCharByte = countCharByte + 1
		End If
	Next
End Function

This optimization doesn't apply to all string operations. Depending on the nature of your problem, you'll see anything from fantastic improvement to slight degradation. Be sure to test both ways.

Russell Jones
 
Comment and Contribute

 

 

 

 

 


(Maximum characters: 1200). You have 1200 characters left.

 

 

Sitemap