JuliaLang / julia

The Julia Programming Language
https://julialang.org/
MIT License
45.73k stars 5.49k forks source link

print(iobuffer, number) without calling string(number)? #55835

Open stevengj opened 1 month ago

stevengj commented 1 month ago

Related to a discussion on Discourse, I noticed that show(io, number) defaults to write(io, string(number)) or similar (see here for integers and here for floats). This involves allocating a temporary buffer. However, if io is an IOBuffer, we should be able to use the IOBuffer itself as the buffer to write into, saving us an allocation.

It seems fairly straightforward to fix this, albeit tedious. Basically some refactoring of the existing string(n) methods a function that takes a pre-allocated buffer, which can be a view into the IOBuffer or a new StringVector as needed.

stevengj commented 1 month ago

Note that the same mechanism could also be exploited by https://github.com/JuliaIO/BufferedStreams.jl

oscardssmith commented 1 month ago

I looked into this and the annoying part is that you need to write the integer backwards and it's unclear how to do that

stevengj commented 1 month ago

Why is this a problem? For IOBuffer, you have an array under the hood. Once you allocate space for the output and provide a view of the internal buffer, you can write to it in any order you want. It will be exactly the current code that writes to a StringVector(n), just refactored to take the array to write to as input.

For a generic IO stream, we'll want to continue allocating a string first and then writing it all at once. I'm not advocating character-by-character writes to arbitrary streams.