I test three methods. First, Alain’s suggestion, second, the implementation in M_String and StringUtils, and finally, Tim’s suggestion. That also worked out slowest to fastest:
The code:
[code
const kRepetitions = 1000
const kSpaceCount = 100
#if not DebugBuild
#pragma BackgroundTasks False
#pragma NilObjectChecking False
#pragma StackOverflowChecking False
#pragma BoundsChecking False
#endif
dim msg as string
dim sw as new Stopwatch_MTC
sw.Start
for i as integer = 1 to kRepetitions
dim arr() as string
redim arr( kSpaceCount )
dim s as string = join( arr, " " )
next
sw.Stop
msg = “With arr: " + format( sw.ElapsedMicroseconds, “#,” ) + " microsecs”
AddToResult msg
sw.Reset
sw.Start
for i as integer = 1 to kRepetitions
dim spaces as string = " "
dim l as integer = 1
dim halfLen as integer = ( kSpaceCount + 1 ) \\ 2
while l < halfLen
spaces = spaces + spaces
l = l + l
wend
dim diff as integer = kSpaceCount - l
dim s as string = spaces + spaces.Left( diff )
next
sw.Stop
msg = “Doubling: " + format( sw.ElapsedMicroseconds, “#,” ) + " microsecs”
AddToResult msg
sw.Reset
sw.Start
dim spaces as string = " "
dim spacesLen as integer = spaces.Len
for i as integer = 1 to kRepetitions
while spacesLen < kSpaceCount
spaces = spaces + spaces
spacesLen = spacesLen + spacesLen
wend
dim s as string = spaces.Left( kSpaceCount )
next
sw.Stop
msg = “Remembering: " + format( sw.ElapsedMicroseconds, “#,” ) + " microsecs”
AddToResult msg
[/code]
Typical results from a compiled app, two consecutive runs:
With arr: 2,715 microsecs
Doubling: 1,684 microsecs
Remembering: 301 microsecs
With arr: 2,574 microsecs
Doubling: 1,639 microsecs
Remembering: 321 microsecs