Skip to content

Commit 370d452

Browse files
committed
perf: optimize permutations (increment! loop)
- The construct previously used in the `for` loop is inefficient. - The loop can exit early as soon as `state[i] <= max` is satisfied. - All array indexing can be marked `@inbounds`.
1 parent ab33a23 commit 370d452

File tree

1 file changed

+8
-6
lines changed

1 file changed

+8
-6
lines changed

src/permutations.jl

Lines changed: 8 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -28,12 +28,14 @@ function has_repeats(state::Vector{Int})
2828
end
2929

3030
function increment!(state::Vector{Int}, min::Int, max::Int)
31-
state[end] += 1
32-
for i in reverse(eachindex(state))[firstindex(state):end-1]
33-
if state[i] > max
34-
state[i] = min
35-
state[i-1] += 1
36-
end
31+
# All array indexing can be marked inbounds because of the type restriction in the signature.
32+
# If the type restriction is ever loosened, please check safety of the `@inbounds`.
33+
@inbounds state[end] += 1
34+
i = lastindex(state)
35+
@inbounds while i > firstindex(state) && state[i] > max
36+
state[i] = min
37+
state[i-1] += 1
38+
i -= 1
3739
end
3840
end
3941

0 commit comments

Comments
 (0)