Atlanta Custom Software Development 

 
   Search        Code/Page
 

User Login
Email

Password

 

Forgot the Password?
Services
» Web Development
» Maintenance
» Data Integration/BI
» Information Management
Programming
  Database
Automation
OS/Networking
Graphics
Links
Tools
» Regular Expr Tester
» Free Tools

Swap strings the fast way
[ All Languages » VB »  String]

Total Hit ( 3332)

Rate this article:     Poor     Excellent 

 Submit Your Question/Comment about this article

Rating


 


Consider the usual way of swapping two strings:

Click here to copy the following block
Dim s1 As String, s2 As String
Dim tmp As String

' initialize the strings
s1 = String$(1000, "-")
s2 = String$(1500, "+")
' do the swap, through a temporary variable
tmp = s1
s1 = s2
s2 = tmp

If you put the above code in a time-critical loop (such as when you are sorting an array) and the strings you're working with are rather long, this code becomes relatively slow, because it has to allocate a new string, copy a lot of characters, and then deallocate the memory for the temporary strings used in the meantime.
A more linear approach consists of just exchanging the contents of the string descriptors for the two s1 and s2 strings, withouth actually moving any character in memory and, above all, without having to allocate and release memory. The following code can be 20+ faster than the previous approach, depending on how long the strings you're processing are:

Click here to copy the following block
Private Declare Sub CopyMemory Lib "kernel32" Alias "RtlMoveMemory" (dest As _
  Any, source As Any, ByVal numBytes As Long)

Dim saveAddr As Long

' save the descriptor of first string
saveAddr = StrPtr(s1)
' copy the s2's descriptor into s1's descriptor (32 bit)
CopyMemory ByVal VarPtr(s1), ByVal VarPtr(s2), 4
' complete the swapping of descriptors
CopyMemory ByVal VarPtr(s2), saveAddr, 4


Submitted By : Nayan Patel  (Member Since : 5/26/2004 12:23:06 PM)

Job Description : He is the moderator of this site and currently working as an independent consultant. He works with VB.net/ASP.net, SQL Server and other MS technologies. He is MCSD.net, MCDBA and MCSE. In his free time he likes to watch funny movies and doing oil painting.
View all (893) submissions by this author  (Birth Date : 7/14/1981 )


Home   |  Comment   |  Contact Us   |  Privacy Policy   |  Terms & Conditions   |  BlogsZappySys

© 2008 BinaryWorld LLC. All rights reserved.