Skip to content

Commit

Permalink
Merge pull request #17707 from pabloferz/pz/ntuple
Browse files Browse the repository at this point in the history
Speed up ntuple (fixes #17703)
  • Loading branch information
JeffBezanson authored Jul 31, 2016
2 parents d4a29e5 + 4aa9de5 commit b7caa1d
Show file tree
Hide file tree
Showing 2 changed files with 18 additions and 7 deletions.
17 changes: 10 additions & 7 deletions base/tuple.jl
Original file line number Diff line number Diff line change
Expand Up @@ -63,13 +63,16 @@ end
## mapping ##

ntuple(f::Function, n::Integer) =
n<=0 ? () :
n==1 ? (f(1),) :
n==2 ? (f(1),f(2),) :
n==3 ? (f(1),f(2),f(3),) :
n==4 ? (f(1),f(2),f(3),f(4),) :
n==5 ? (f(1),f(2),f(3),f(4),f(5),) :
tuple(ntuple(f,n-5)..., f(n-4), f(n-3), f(n-2), f(n-1), f(n))
n <= 0 ? () :
n == 1 ? (f(1),) :
n == 2 ? (f(1),f(2),) :
n == 3 ? (f(1),f(2),f(3),) :
n == 4 ? (f(1),f(2),f(3),f(4),) :
n == 5 ? (f(1),f(2),f(3),f(4),f(5),) :
n < 16 ? (ntuple(f,n-5)..., f(n-4), f(n-3), f(n-2), f(n-1), f(n)) :
_ntuple(f, n)

_ntuple(f::Function, n::Integer) = (@_noinline_meta; ((f(i) for i = 1:n)...))

# inferrable ntuple
function ntuple{F,N}(f::F, ::Type{Val{N}})
Expand Down
8 changes: 8 additions & 0 deletions test/tuple.jl
Original file line number Diff line number Diff line change
Expand Up @@ -162,3 +162,11 @@ end

# issue #12854
@test_throws TypeError ntuple(identity, Val{1:2})

for n = 0:20
t = ntuple(identity, n)
@test length(t) == n
for i = 1:n
@test t[i] == i
end
end

0 comments on commit b7caa1d

Please sign in to comment.