Skip to content

Commit 44bef0d

Browse files
gdallestevengj
andauthored
Improve printing of several arguments (#55754)
Following a discussion on [Discourse](https://discourse.julialang.org/t/string-optimisation-in-julia/119301/10?u=gdalle), this PR tries to improve `print` (and variants) for more than one argument. The idea is that `for` is type-unstable over the tuple `args`, while `foreach` unrolls. --------- Co-authored-by: Steven G. Johnson <[email protected]>
1 parent 220742d commit 44bef0d

File tree

1 file changed

+5
-19
lines changed

1 file changed

+5
-19
lines changed

base/strings/io.jl

+5-19
Original file line numberDiff line numberDiff line change
@@ -42,9 +42,7 @@ end
4242
function print(io::IO, xs...)
4343
lock(io)
4444
try
45-
for x in xs
46-
print(io, x)
47-
end
45+
foreach(Fix1(print, io), xs)
4846
finally
4947
unlock(io)
5048
end
@@ -138,32 +136,20 @@ function print_to_string(xs...)
138136
if isempty(xs)
139137
return ""
140138
end
141-
siz::Int = 0
142-
for x in xs
143-
siz += _str_sizehint(x)
144-
end
145-
# specialized for performance reasons
139+
siz = sum(_str_sizehint, xs; init = 0)
146140
s = IOBuffer(sizehint=siz)
147-
for x in xs
148-
print(s, x)
149-
end
141+
print(s, xs...)
150142
String(_unsafe_take!(s))
151143
end
152144

153145
function string_with_env(env, xs...)
154146
if isempty(xs)
155147
return ""
156148
end
157-
siz::Int = 0
158-
for x in xs
159-
siz += _str_sizehint(x)
160-
end
161-
# specialized for performance reasons
149+
siz = sum(_str_sizehint, xs; init = 0)
162150
s = IOBuffer(sizehint=siz)
163151
env_io = IOContext(s, env)
164-
for x in xs
165-
print(env_io, x)
166-
end
152+
print(env_io, xs...)
167153
String(_unsafe_take!(s))
168154
end
169155

0 commit comments

Comments
 (0)