While SWAP is simple to use, it is typically faster for all but integer types. A proxy-type swap is usually faster for integer types. As always, if speed is critical, test the alternatives IN YOUR PROGRAM.
My test code:
Code: Select all
type udt
ii as integer
ss as string
end type
dim as udt uu1, uu2, uuproxy
dim as string sa, sb, sproxy
dim as integer ia, ib, iproxy
dim as integer count
'count = 10000
count = 1000000
'count = 100000000
dim as double xxtime, stime1, stime2, stime3
dim as double ptime1, ptime2, ptime3
sa = "test"
sb = "text"
ia = 44
ib = -124
uu1.ii = ia
uu1.ss = sa
uu2.ss = sb
uu2.ii = ib
xxtime = timer
for y as integer = 1 to count
swap ia, ib
next
stime1 = timer - xxtime
sleep 5,1
xxtime = timer
for y as integer = 1 to count
swap sa, sb
next
stime2 = timer - xxtime
sleep 5,1
xxtime = timer
for y as integer = 1 to count
swap uu1, uu2
next
stime3 = timer - xxtime
sleep 5,1
xxtime = timer
for y as integer = 1 to count
iproxy = ia
ia = ib
ib = iproxy
next
ptime1 = timer - xxtime
sleep 5,1
xxtime = timer
for y as integer = 1 to count
sproxy = sa
sa = sb
sb = sproxy
next
ptime2 = timer - xxtime
sleep 5,1
xxtime = timer
for y as integer = 1 to count
uuproxy = uu1
uu1 = uu2
uu2 = uuproxy
next
ptime3 = timer - xxtime
print tab(9); "swap time"; tab(38); "proxy time"
print
print " int: "; stime1; tab(36); ptime1
print " str: "; stime2; tab(36); ptime2
print " udt: "; stime3; tab(36); ptime3
print
print "integer swap/proxy ratio: "; stime1/ptime1
print
Results shown are for program provided.david@deb9:~/Desktop$ ./test
-------- swap time------------------------------ proxy time
int -- 0.008764028549194336 ------------ 0.003302097320556641
str -- 0.007848978042602539 ------------ 0.04162502288818359
udt -- 0.009058952331542969 ------------ 0.05147504806518555
integer swap/proxy ratio: 2.654079422382671
string proxy/swap ratio: 5.303241092311898
udt proxy/swap ratio: 5.682229708390357
With this code, it varies between 2.5+ up to 3 times slower on my usual test/coding system.
A LARGE caveat: For the integers SWAP is very code touchy.
With other code and on other machines, I have seen it as much as 6 times slower.
BUT ---
For my PI3B+ (4 core) and this same system (Debian w/6 core AMD) - the higher and the lower counts in the code above BOTH gave an integer .9 ratio !!
I would be interested to hear what differences others see, or if someone could even suggest why integer SWAP is so touchy.
Thanks
david