days keysAndValuesDo: [:key :value |
    Transcript print: key; nextPutAll: ' has '; print: value;
nextPutAll: ' days'; cr].
Transcript endEntry.
works too and in some Smalltalks is easily the most efficient approach, as it
does not construct any strings you have no other use for.

In Pharo, however, there is a reason to prefer
    Transcript nextPutAll: (key asString, ' has ', value asString, '
days', String cr).
The reason is that in Pharo 7, Transcript is an instance of
*ThreadSafe*Transcript,
and each public operation like #nextPut: or #print: locks the stream.
In fact we have
    show: anObject
      self critical: [self print: anObject; endEntry].
    print: anObject
      self nextPutAll: anObject asString.
    nextPutAll: aString
      self critical: [stream nextPutAll: aString].
      ^aString
    cr
      self nextPut: Character cr.
    nextPut: aCharacter
      self critical: [stream nextPut: aCharacter].
      ^aCharacter

So the code I exhibited second (using #nextPutAll:) locks the Transcript *once*
ensuring that nothing else can be written between 'days' and cr, whereas both
versions you exhibited have a timing window between #show: and #cr where
another Smalltalk process could write something.

But you are asking about the difference between #asString and #printString.
So look up the definitions!  In a Playground, type
asString
and then Ctrl-m (for iMplementors).  We see almost at once that
Object>>
    asString
      ^self printString
so that for numbers there is NO difference between the two (except a
little bit of
overhead for #asString).  But we also see
String>>
    asString
      ^self
Symbol>>
    asString
      "complicated code logically equivalent to"
      ^String withAll: self
Just for grins, the following interaction was with GNU Smalltalk.
st> #January asString
'January'
st> #January printString
'#January'
st> 31 asString
'31'
st> 31 printString
'31'
Pharo does exactly the same.

On Sun, 13 Oct 2019 at 23:51, Samuel Teixeira Santos
<arcano...@gmail.com> wrote:
>
> Hi folks.
> I'm starting in Pharo studies by FUN Mooc.
> In Week 03, on An Overview of Essential Collections there is the example 
> below:
>
> | days |
> days := Dictionary new.
>
> days
> at: #January put: 31;
> at: #February put: 28;
> at: #March put: 31.
>
> days keysAndValuesDo:
> [ :k :v | Transcript show: k asString, ' has ', v printString, ' days'
> ; cr ]
>
> The code in blue I change for
>
> days keysAndValuesDo:
> [ :k :v | Transcript show: k asString, ' has ', v asString, ' days'
> ; cr ]
>
> And works too on Playground.
>
> There is something different about both? There is someone better than other?
>
> Thanks in advance,
>
>
> Samuel T. Santos

Reply via email to