Confusion about to_s

while reading asterite’s blog post about incremental-compilation
Incremental compilation for Crystal - Part 3 - DEV Community,

it says io.cr has dependencies on foo.
A piece that puzzles me is why crystal choose this protocol of to_s(io) ?
in ruby you define to_s

def to_s
  ...
end

if some io wants to use it
then just io << xxx.to_s, which is simpler

in python is similar,

def __str__(self):
   ...

why crystal choose this protocol?

There’s a section in the reference book about this: Performance - Crystal

This philosophy of appending to an IO instead of returning an intermediate string results in better performance than handling intermediate strings.

EDIT: You can however still override def to_s : String instead of the IO version. This can be useful if you already have the string representation in memory (such as within an ivar) to save some additional memory.

1 Like