[squeak-dev] Xtreams question - OC of chars to String

Levente Uzonyi leves at elte.hu
Sat Dec 29 18:47:45 UTC 2012


On Sat, 29 Dec 2012, Chris Cunnington wrote:

> I have a question about converting an OrderedCollection full of chars into a 
> string. [1]

| oc |
oc := #($a $b $c) asOrderedCollection.
oc as: String.

>
> I would have thought there was a method like #asString that could be sent to 
> an OrderedCollection to produce a string. I find myself having to do the 
> process in three steps: 1) #reading the OC; 2) creating an empty string; and 
> then, 3) iterating over every char to put it into the String.

Since the size of Strings (or an instance of a variable class in general) 
can't be changed, therefore creating an empty String and concatenating to 
it one character at a time is a bad pattern in Smalltalk. Your algorithm 
will need O(n^2) time to finish (where n is the number of characters), and 
you'll also waste O(n^2) space, which will make your code even slower, 
since the intermediate collections will have to be garbage collected.


Levente

>
> I think I'm missing a simpler way. Especially with Xtreams. Shouldn't I just 
> use a filter, change the #contentSpecies, or something?
>
> Chris
>
>
> [1]
>
> startTag: data
>    <action: 'element'>
>    |tagdata str |
>    tagdata := data second first reading.
>    str := (String new: 20) writing.
>    tagdata do: [:each| str put: each].
>    ^'html ' , (data first second first asString) , $: , $' , (str close; 
> terminal) , $'
>
>
>


More information about the Squeak-dev mailing list