Skip to content

Commit

Permalink
improve performance for string of ::Char
Browse files Browse the repository at this point in the history
  • Loading branch information
KristofferC committed Aug 24, 2018
1 parent d55b044 commit d511834
Showing 1 changed file with 21 additions and 13 deletions.
34 changes: 21 additions & 13 deletions base/strings/io.jl
Expand Up @@ -103,31 +103,39 @@ function sprint(f::Function, args...; context=nothing, sizehint::Integer=0)
String(resize!(s.data, s.size))
end

tostr_sizehint(x) = 0
tostr_sizehint(x) = 8
tostr_sizehint(x::AbstractString) = lastindex(x)
tostr_sizehint(x::Float64) = 20
tostr_sizehint(x::Float32) = 12

function print_to_string(xs...; env=nothing)
function print_to_string(xs...)
if isempty(xs)
return ""
end
siz = 0
for x in xs
siz += tostr_sizehint(xs[1])
end
# specialized for performance reasons
s = IOBuffer(sizehint=tostr_sizehint(xs[1]))
if env !== nothing
env_io = IOContext(s, env)
for x in xs
print(env_io, x)
end
else
for x in xs
print(s, x)
end
s = IOBuffer(sizehint=siz)
for x in xs
print(s, x)
end
String(resize!(s.data, s.size))
end

string_with_env(env, xs...) = print_to_string(xs...; env=env)
function string_with_env(env, xs...)
if isempty(xs)
return ""
end
# specialized for performance reasons
s = IOBuffer(sizehint=tostr_sizehint(xs[1]))
env_io = IOContext(s, env)
for x in xs
print(env_io, x)
end
String(resize!(s.data, s.size))
end

"""
string(xs...)
Expand Down

0 comments on commit d511834

Please sign in to comment.