I found that some of the functions in Base are written like (::IO,::Any), and then uses sprint to wrap it so that it can return a string.
For the following code:
function A(io::IO)
print(io,"foo")
end
A()=sprint(A)
B()="foo"
B(io::IO)=print(io,B())
Which is quicker, A or B (maybe in more complicated cases than a single “foo”), and why?
If one of them is quicker, does the conclusion also work for inputting(using IOBuffer to wrap a string)?
It’s usually written that way to save allocations. Strings in julia are immutable, so if you don’t actually need a string and just want to write some result somewhere (possibly on disk, to a socket, …), you can just pass the IO around instead. As such, “which is quicker” depends on your context, e.g. if you really do need a String you’re not really going to get around creating it.
Well, I couldn’t answer that precisely because what’s quicker depends on how it’s used and what exactly you mean with that Benchmarking your use case is definitely the way to go, but having an API that takes an IO that you explicitly print to is (generally) going to be easier to optimize because you don’t create new strings all the time. Wrapping that in a function that passes an IOBuffer you then convert to a string will probably be fast.