Sunday, August 20, 2006

[VB6] Working with strings

When you work with strings it's ussual to see something like this:

VB6:
Dim str As String
str = "Select * from "
str = str & " Table1 where"
str = str & " Table1.Id=" & MyId

well, in this case, each operation (the join of strings) performs at least 2 tasks before returning the new string:
- first a memory space in ram is reserved for the new string (size1 + size2)
- then the join of the strings is performed (each character of each string is copied to the new space in ram)
and finally the pointer to that memory position is returned to the final string.

In Java you can use the StringBuffer class, this object performs this tasks faster than the previous example, in .NET Framework you can use the StringBuilder class to perform the same tasks.

But what about VB6, here's what you can do:
'Start of class definition
Private group() As String
Private lngItems As Long

Public Sub Add(ByVal str As String)
ReDim Preserve group(lngItems) As String
group(lngItems) = str
lngItems = lngItems + 1
End Sub

Public Function toString() As String
If lngItems > 0 Then toString = Join(group, "")
End Function
'End of class definition

Join is an API function in VB6 that join slots of memory into one single slot, and it's performed really fast, so, this can help you if you want to cut some time on your operations.

I've also heard some tips, like it's faster to compare:

If MyString = vbNullString Then ...

Than

If MyString = "" Then ...

If you do this often in a one task job, then following this tips may help you. Have fun!.

1 Comments:

At 2:20 AM, Anonymous Anonymous said...

This comment has been removed by a blog administrator.

 

Post a Comment

<< Home