Why are stdout, stderr etc. not const global variables?

I can overwrite their values (in Julia 1.9.0):

julia> Base.stderr = Base.stdout
Base.TTY(RawFD(13) open, 0 bytes waiting)

So whenever I write
print(stderr, "some message")
I’m using a non-const global variable from Base, which is not ideal for performance?

I found this out when I was trying JET.jl. The @report_opt tool complained about “runtime dispatch” for every line of my code that printed to stderr.

They can’t be const because you can change them (with redirect_stdout etc).

Typically, writing to stdout and stderr is not going to be performance critical, so the overhead of dynamic dispatch isn’t going to matter.

If you do have performance-critical I/O, it should generally be in a function that takes an io::IO argument so that it can write to an arbitrary stream (not just to stdout). In this case, the cost of dynamic dispatch is paid only once, when you call that function, not on every print(io, ...) call within the function.

4 Likes