Swap strings the fast way

Consider the usual way of swapping two strings:

Dim s1 As String, s2 As StringDim tmp As String' initialize the strings s1 = String$(1000, "-")s2 = String$(1500, "+")' do the swap, through a temporary variabletmp = s1s1 = s2s2 = 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:

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 stringsaveAddr = 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 descriptorsCopyMemory ByVal VarPtr(s2), saveAddr, 4

Share the Post:
Share on facebook
Share on twitter
Share on linkedin

Overview

The Latest

homes in the real estate industry

Exploring the Latest Tech Trends Impacting the Real Estate Industry

The real estate industry is changing thanks to the newest technological advancements. These new developments — from blockchain and AI to virtual reality and 3D printing — are poised to change how we buy and sell homes. Real estate brokers, buyers, sellers, wholesale real estate professionals, fix and flippers, and beyond may

man on floor with data

DevX Quick Guide to Data Ingestion

One of the biggest trends of the 21st century is the massive surge in internet usage. With major innovations such as smart technology, social media, and online shopping sites, the internet has become an essential part of everyday life for a large portion of the population. Due to this internet

payment via phone

7 Ways Technology Has Changed Traditional Payments

In today’s digital world, technology has changed how we make payments. From contactless cards to mobile wallets, it’s now easier to pay for goods and services without carrying cash or using a checkbook. This article will look at seven of the most significant ways technology has transformed traditional payment methods.