[Newbies] [Q] How should one concatenate Strings?
Damien Cassou
damien.cassou at laposte.net
Tue May 9 18:59:50 UTC 2006
> If you are building very long strings by using , in an inner loop, it
> can be slow because you will have an N squared algorithm. You can
> convert that into a linear time algorithm by writing to an WriteStream
> using nextPut: and nextPutAll: and then asking the WriteStream for its
> contents. It leads to a little more complicated code, but on some
> programs in can create a dramatic performance improvement. In
> general, though, use "comma", since it is simpler.
You should avoid optimizing your code before making sure it needs an
improvement. Nevertheless, here is a simple benchmark for the two
techniques:
[| temp |
temp := String new.
(1 to: 100000)
do: [:i | temp := temp, i asString]] timeToRun
Answers 75.202 milliseconds
[| temp |
temp := WriteStream on: String new.
(1 to: 100000)
do: [:i | temp nextPutAll: i asString]] timeToRun
Answers 3.169 milliseconds
To get the string back from the Stream, use #contents:
myWriteStream contents
Bye
--
Damien Cassou
More information about the Beginners
mailing list