Another way to speed up concatenation
Posted: Sat May 07, 2016 3:44 am
I'm not sure will it be useful for someone on practice, just worked this night on some code processing strings and raised following idea as side-effect. The typical way to speed up string merging is to use pre-allocated buffer and writing to it by using kind of direct memory access [and any other trick to avoid iteration of whole 0-terminated string everytime], and I wondered that following code is fast enough too while not doing so
Seems to be about 10x faster than regular concatenation.

Seems to be about 10x faster than regular concatenation.
Code: Select all
EnableExplicit
DisableDebugger
OpenConsole("Testing facility")
Define.i Time
Define.i Counter, Count
Count = 500000
Define A$
Define B$, C$, D
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
; case A, regular
Time = ElapsedMilliseconds()
For Counter = 1 To Count
A$ + "a"
Next Counter
Time = ElapsedMilliseconds() - Time
PrintN("Cycle 1: " + Str(Time) + "ms")
;---------------------------------------------;
; case B. C$ variable used as buffer which is added to B$ and flushed with some interval
Time = ElapsedMilliseconds()
For Counter = 1 To Count
C$ + "a" ; instead of adding directly to B$
D + 1
If D % 50000 = 0 ; clear every N chars
B$ + C$
C$ = ""
EndIf
Next Counter
Time = ElapsedMilliseconds() - Time
PrintN("Cycle 2: " + Str(Time) + "ms")
; print here len of A and B to check if all ok
PrintN(Str(Len(A$)))
PrintN(Str(Len(B$)))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
Input()