From b1c2d7357ab1cd4129c5a9049c17be0377276540 Mon Sep 17 00:00:00 2001 From: "Steven G. Johnson" Date: Sat, 24 Jun 2017 13:50:40 -0400 Subject: [PATCH] optimize repeat(string, n) for repeating single ASCII chars (#22462) --- base/strings/string.jl | 8 ++++++-- test/strings/basic.jl | 4 ++++ 2 files changed, 10 insertions(+), 2 deletions(-) diff --git a/base/strings/string.jl b/base/strings/string.jl index f55681cda86c7..2a17ddb041dfc 100644 --- a/base/strings/string.jl +++ b/base/strings/string.jl @@ -427,8 +427,12 @@ function repeat(s::String, r::Integer) r < 0 && throw(ArgumentError("can't repeat a string $r times")) n = s.len out = _string_n(n*r) - for i=1:r - unsafe_copy!(pointer(out, 1+(i-1)*n), pointer(s), n) + if n == 1 # common case: repeating a single ASCII char + ccall(:memset, Ptr{Void}, (Ptr{UInt8}, Cint, Csize_t), out, unsafe_load(pointer(s)), r) + else + for i=1:r + unsafe_copy!(pointer(out, 1+(i-1)*n), pointer(s), n) + end end return out end diff --git a/test/strings/basic.jl b/test/strings/basic.jl index bf1fb7741c862..747e92151b508 100644 --- a/test/strings/basic.jl +++ b/test/strings/basic.jl @@ -462,6 +462,10 @@ Base.endof(x::CharStr) = endof(x.chars) @test cmp("\U1f596\U1f596", CharStr("\U1f596")) == 1 # Gives BoundsError with bug @test cmp(CharStr("\U1f596"), "\U1f596\U1f596") == -1 +# repeat function +@test repeat("xx",3) == repeat("x",6) == "xxxxxx" +@test repeat("αα",3) == repeat("α",6) == "αααααα" + # issue #12495: check that logical indexing attempt raises ArgumentError @test_throws ArgumentError "abc"[[true, false, true]] @test_throws ArgumentError "abc"[BitArray([true, false, true])]