dcsimg
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

By submitting your information, you agree that devx.com may send you DevX offers via email, phone and text message, as well as email offers about other products and services that DevX believes may be of interest to you. DevX will process your information in accordance with the Quinstreet Privacy Policy.


Tip of the Day
Language: Visual Basic
Expertise: Advanced
Nov 18, 1999

WEBINAR:

On-Demand

Building the Right Environment to Support AI, Machine Learning and Deep Learning


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 = Save
End 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 = Save
End Sub
But as the strings grow in length, the speed difference gets more and more dramatic.
Thomas Weiss
 
Comment and Contribute

 

 

 

 

 


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

 

 

Sitemap
Thanks for your registration, follow us on our social networks to keep up-to-date