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 May 18, 2023
1 parent ce1ecd2 commit a7278d7
Showing 1 changed file with 12 additions and 7 deletions.
19 changes: 12 additions & 7 deletions base/strings/io.jl
Original file line number Diff line number Diff line change
Expand Up @@ -979,18 +979,23 @@ end

function print(io::IO, s::Union{<:StyledString, SubString{<:StyledString}})
if get(io, :color, false) == true
lastface = FACES[:default]
buf = IOBuffer() # Avoid the overhead in repeatadly printing to `stdout`
lastface::Face = FACES[:default]
for (str, styles) in eachstyle(s)
face = getface(styles)
link = let idx=findfirst(==(:link) first, styles)
if !isnothing(idx) last(styles[idx]) end end
!isnothing(link) && print(io, "\e]8;;", link, "\e\\")
termstyle(io, face, lastface)
print(io, str)
!isnothing(link) && print(io, "\e]8;;\e\\")
if !isnothing(idx)
string(last(styles[idx]))::String
end end
!isnothing(link) && print(buf, "\e]8;;", link, "\e\\")
termstyle(buf, face, lastface)
print(buf, str)
!isnothing(link) && print(buf, "\e]8;;\e\\")
lastface = face
end
termstyle(io, FACES[:default], lastface)
termstyle(buf, FACES[:default], lastface)
write(io, take!(buf))
nothing
elseif s isa StyledString
print(io, s.string)
elseif s isa SubString
Expand Down

0 comments on commit a7278d7

Please sign in to comment.