For completeness, here is a speed test to see which method is fastest. It includes dodicat's macro. No compiler optimization switches were used.
Code: Select all
' swapping string bytes speed test by Munair
' ----------------------------------------------------------------
declare sub SwapInstr1(s as string, a as ubyte, b as ubyte)
declare sub SwapInstr2(s as string, a as ubyte, b as ubyte)
declare sub SwapInstr3(s as string, a as ubyte, b as ubyte, c as ubyte, d as ubyte)
#macro switch(a,b)
' about as fast as SwapInstr3
scope
var temp=a
a=b
b=temp
end scope
#endmacro
dim s as string = "001111"
dim i as uinteger
dim t as double
print "with bytes:"
t = timer
for i = 0 to 100000000
SwapInstr1(s, 0, 4)
SwapInstr1(s, 1, 5)
next
print timer - t
print "with bytes using swap():"
t = timer
for i = 0 to 100000000
SwapInstr2(s, 0, 4)
SwapInstr2(s, 1, 5)
next
print timer - t
print "with mid:"
t = timer
for i = 0 to 100000000
SwapInstr3(s, 5, 2, 1, 2)
next
print timer - t
print "with macro(mid, mid):"
t = timer
for i = 0 to 100000000
switch(mid(s, 5, 2), mid(s, 1, 2))
next
print timer - t
end
sub SwapInstr1(s as string, a as ubyte, b as ubyte)
' almost as fast as SwapInstr2
dim temp as ubyte = s[a]
dim l as uinteger = len(s)
if a < l then
if b < l then
s[a] = s[b]
s[b] = temp
end if
end if
end sub
sub SwapInstr2(s as string, a as ubyte, b as ubyte)
' slightly faster than SwapInstr1
dim l as uinteger = len(s)
if a < l then
if b < l then
swap s[a], s[b]
end if
end if
end sub
sub SwapInstr3(s as string, a as ubyte, b as ubyte, c as ubyte, d as ubyte)
' almost 10 times slower than SwapInstr1 and SwapInstr2
dim tmp as string = mid(s, a, b)
mid(s, a, b) = mid(s, c, d)
mid(s, c, d) = tmp
end sub
Output:
Code: Select all
1. with bytes:
1.470577001571655
2. with bytes using swap():
1.368752956390381
3. with mid:
9.857635974884033
4. with macro(mid, mid):
9.665795087814331
Tested on Manjaro x64 with fbc 1.08: