Skip to content

Commit adc8422

Browse files
committed
Buffer styled printing
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.
1 parent c5798b2 commit adc8422

File tree

1 file changed

+12
-7
lines changed

1 file changed

+12
-7
lines changed

base/strings/io.jl

Lines changed: 12 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -977,18 +977,23 @@ end
977977

978978
function print(io::IO, s::Union{<:StyledString, SubString{<:StyledString}})
979979
if get(io, :color, false) == true
980-
lastface = FACES[:default]
980+
buf = IOBuffer() # Avoid the overhead in repeatadly printing to `stdout`
981+
lastface::Face = FACES[:default]
981982
for (str, styles) in eachstyle(s)
982983
face = getface(styles)
983984
link = let idx=findfirst(==(:link) first, styles)
984-
if !isnothing(idx) last(styles[idx]) end end
985-
!isnothing(link) && print(io, "\e]8;;", link, "\e\\")
986-
termstyle(io, face, lastface)
987-
print(io, str)
988-
!isnothing(link) && print(io, "\e]8;;\e\\")
985+
if !isnothing(idx)
986+
string(last(styles[idx]))::String
987+
end end
988+
!isnothing(link) && print(buf, "\e]8;;", link, "\e\\")
989+
termstyle(buf, face, lastface)
990+
print(buf, str)
991+
!isnothing(link) && print(buf, "\e]8;;\e\\")
989992
lastface = face
990993
end
991-
termstyle(io, FACES[:default], lastface)
994+
termstyle(buf, FACES[:default], lastface)
995+
write(io, take!(buf))
996+
nothing
992997
elseif s isa StyledString
993998
print(io, s.string)
994999
elseif s isa SubString

0 commit comments

Comments
 (0)