Skip to content

Commit

Permalink
Buffer styled printing
Browse files Browse the repository at this point in the history
When printing directly to stdout, there is a non-negligible overhead
compared to simply printing to an IOBuffer. Testing indicates 3
allocations per print argument, and benchmarks reveal a ~2x increase in
allocations overall and much as a 10x increase in execution time.

Thus, it seems worthwhile to use a temporary buffer in all cases.
  • Loading branch information
tecosaur committed Oct 20, 2023
1 parent 13f32f1 commit ea24b53
Showing 1 changed file with 8 additions and 5 deletions.
13 changes: 8 additions & 5 deletions base/strings/io.jl
Original file line number Diff line number Diff line change
Expand Up @@ -1004,19 +1004,22 @@ end
function _ansi_writer(io::IO, s::Union{<:StyledString, SubString{<:StyledString}},
string_writer::Function)
if get(io, :color, false)::Bool
buf = IOBuffer() # Avoid the overhead in repeatadly printing to `stdout`
lastface::Face = FACES.current[][:default]
for (str, styles) in eachstyle(s)
face = getface(styles)
link = let idx=findfirst(==(:link) first, styles)
if !isnothing(idx)
string(last(styles[idx]))::String
end end
!isnothing(link) && write(io, "\e]8;;", link, "\e\\")
termstyle(io, face, lastface)
string_writer(io, str)
!isnothing(link) && write(io, "\e]8;;\e\\")
!isnothing(link) && write(buf, "\e]8;;", link, "\e\\")
termstyle(buf, face, lastface)
string_writer(buf, str)
!isnothing(link) && write(buf, "\e]8;;\e\\")
lastface = face
end
termstyle(io, getface(), lastface)
termstyle(buf, getface(), lastface)
write(io, take!(buf))
elseif s isa StyledString
string_writer(io, s.string)
elseif s isa SubString
Expand Down

0 comments on commit ea24b53

Please sign in to comment.