String optimisation in Julia

This is because for loops over a heterogeneous tuple are type-unstable. As discussed in For statement type instability - #7 by stevengj, however, it’s possible to fix this by unrolling, and should be a simple 1-line patch to change the print definition to something like:

function myprint(io::IO, xs...)
    lock(io)
    try
        foreach(xs) do x
            print(io, x)
        end
    finally
        unlock(io)
    end
    return nothing
end

which should be type-stable and hopefully should perform better. (Similarly for Base.print_to_string and Base.string_with_env.) Anyone want to submit a PR?

As for write(io, string(n)) vs. print(io, n), I’m not sure what is going on (if there is really a difference?), because print(io, n) calls show(io, n) which calls write(io, string(n)) already?

(However, the fact that writing an integer to a stream requires allocation of a string, for string(n), is certainly hurting us in writing to an IOBuffer where writes are fast. At least in the IOBuffer case, we should in principle be able to use a view into the IOBuffer itself as the necessary buffer. The downside of this would be needing a long list of specialized IOBuffer methods for show, unless we do some clever refactoring.)

6 Likes