Skip to content

Commit

Permalink
make randstring 25% faster for ASCII (JuliaLang#44264)
Browse files Browse the repository at this point in the history
This uses `_string_n` instead of `StringVector` in order to allocate less,
e.g.:
```
julia> @Btime randstring() # master
  71.499 ns (2 allocations: 96 bytes)
"DZk2V5Bm"

julia> @Btime randstring() # PR
  57.832 ns (1 allocation: 32 bytes)
"Hj5PINXU"
```
  • Loading branch information
rfourquet committed May 9, 2022
1 parent a86c687 commit ff45fdc
Showing 1 changed file with 11 additions and 3 deletions.
14 changes: 11 additions & 3 deletions stdlib/Random/src/misc.jl
Original file line number Diff line number Diff line change
Expand Up @@ -71,12 +71,20 @@ function randstring end

let b = UInt8['0':'9';'A':'Z';'a':'z']
global randstring

function randstring(r::AbstractRNG, chars=b, n::Integer=8)
T = eltype(chars)
v = T === UInt8 ? Base.StringVector(n) : Vector{T}(undef, n)
rand!(r, v, chars)
return String(v)
if T === UInt8
str = Base._string_n(n)
GC.@preserve str rand!(r, UnsafeView(pointer(str), n), chars)
return str
else
v = Vector{T}(undef, n)
rand!(r, v, chars)
return String(v)
end
end

randstring(r::AbstractRNG, n::Integer) = randstring(r, b, n)
randstring(chars=b, n::Integer=8) = randstring(default_rng(), chars, n)
randstring(n::Integer) = randstring(default_rng(), b, n)
Expand Down

0 comments on commit ff45fdc

Please sign in to comment.