devxlogo

Swap Strings Faster

Swap Strings Faster

Here’s a cool way to swap strings:

 Declare Sub CopyMemory Lib "kernel32" Alias _	"RtlMoveMemory" (Destination As Any, _	Source As Any, ByVal Length As Long)Sub SwapString(String1 As String, String2 _	As String)	Dim Save As Long	' This code swaps the string descriptors, not 	' the data. StrPtr returns the address of the 	' first character in a string. VarPtr returns 	' the address of a string's descriptor, which 	' is 4 bytes long and contains the address of 	' the first character in the string. StrPtr	' and VarPtr are undocumented VB functions.	Save = StrPtr(String1)	Call CopyMemory(ByVal VarPtr(String1), _		ByVal VarPtr(String2), 4)	Call CopyMemory(ByVal VarPtr(String2), _		Save, 4)End Sub

Even for short strings, this is faster than the traditional method:

 Sub SwapString(String1 As String, String2 _	As String)	Dim Save As String	Save = String1	String1 = String2	String2 = SaveEnd Sub

But as the strings grow in length, the speed difference gets more and more dramatic.Here’s a cool way to swap strings:

 Declare Sub CopyMemory Lib "kernel32" Alias _	"RtlMoveMemory" (Destination As Any, _	Source As Any, ByVal Length As Long)Sub SwapString(String1 As String, String2 _	As String)	Dim Save As Long	' This code swaps the string descriptors, not 	' the data. StrPtr returns the address of the 	' first character in a string. VarPtr returns 	' the address of a string's descriptor, which 	' is 4 bytes long and contains the address of 	' the first character in the string. StrPtr	' and VarPtr are undocumented VB functions.	Save = StrPtr(String1)	Call CopyMemory(ByVal VarPtr(String1), _		ByVal VarPtr(String2), 4)	Call CopyMemory(ByVal VarPtr(String2), _		Save, 4)End Sub

Even for short strings, this is faster than the traditional method:

 Sub SwapString(String1 As String, String2 _	As String)	Dim Save As String	Save = String1	String1 = String2	String2 = SaveEnd Sub

But as the strings grow in length, the speed difference gets more and more dramatic.

See also  How College Students Can Shape the Future of Tech Responsibility
devxblackblue

About Our Editorial Process

At DevX, we’re dedicated to tech entrepreneurship. Our team closely follows industry shifts, new products, AI breakthroughs, technology trends, and funding announcements. Articles undergo thorough editing to ensure accuracy and clarity, reflecting DevX’s style and supporting entrepreneurs in the tech sphere.

See our full editorial policy.

About Our Journalist