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.