Skip to content

Commit dc35b97

Browse files
stevengjvtjnash
authored andcommitted
optimize repeat(string, n) for repeating single ASCII chars (#22462)
(cherry picked from commit b1c2d73)
1 parent 5afab66 commit dc35b97

File tree

2 files changed

+10
-2
lines changed

2 files changed

+10
-2
lines changed

base/strings/string.jl

Lines changed: 6 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -427,8 +427,12 @@ function repeat(s::String, r::Integer)
427427
r < 0 && throw(ArgumentError("can't repeat a string $r times"))
428428
n = s.len
429429
out = _string_n(n*r)
430-
for i=1:r
431-
unsafe_copy!(pointer(out, 1+(i-1)*n), pointer(s), n)
430+
if n == 1 # common case: repeating a single ASCII char
431+
ccall(:memset, Ptr{Void}, (Ptr{UInt8}, Cint, Csize_t), out, unsafe_load(pointer(s)), r)
432+
else
433+
for i=1:r
434+
unsafe_copy!(pointer(out, 1+(i-1)*n), pointer(s), n)
435+
end
432436
end
433437
return out
434438
end

test/strings/basic.jl

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -461,6 +461,10 @@ Base.endof(x::CharStr) = endof(x.chars)
461461
@test cmp("\U1f596\U1f596", CharStr("\U1f596")) == 1 # Gives BoundsError with bug
462462
@test cmp(CharStr("\U1f596"), "\U1f596\U1f596") == -1
463463

464+
# repeat function
465+
@test repeat("xx",3) == repeat("x",6) == "xxxxxx"
466+
@test repeat("αα",3) == repeat("α",6) == "αααααα"
467+
464468
# issue #12495: check that logical indexing attempt raises ArgumentError
465469
@test_throws ArgumentError "abc"[[true, false, true]]
466470
@test_throws ArgumentError "abc"[BitArray([true, false, true])]

0 commit comments

Comments
 (0)