# Performant way to create ntuple?

**URL:** <https://discourse.julialang.org/t/performant-way-to-create-ntuple/5783>\
**Category:** General Usage\
**Tags:** ntuple\
**Created:** [September 8, 2017, 11:23am UTC](https://discourse.julialang.org/t/performant-way-to-create-ntuple/5783 "2017-09-08T11:23:44Z")\
**Posts on this page:** 3\
**Page:** 1

<div class="post-metadata">

**Author:** ![GunnarFarneback](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/gunnarfarneback/32/1827_2.png) [@GunnarFarneback](https://discourse.julialang.org/u/GunnarFarneback)\
**Post date:** [September 8, 2017, 11:23am UTC](https://discourse.julialang.org/t/performant-way-to-create-ntuple/5783/1 "2017-09-08T11:23:44Z")

</div>

Consider the following simplified code for Julia 0.6:

```julia
using BenchmarkTools
@noinline g(x) = x[1]

function f1(M, ::Type{Val{N}}) where N
    s = 0
    for j = 1:M
        x = ntuple(i -> i + j, Val{N})
        s += g(x)
    end
    return s
end

@generated function f2(M, ::Type{Val{N}}) where N
    t = Expr(:tuple, [:($k+j) for k=1:N]...)
    return quote
        s = 0
        for j = 1:M
            x = $t
            s += g(x)
        end
        return s
    end
end

@btime f1(10000, Val{3})
@btime f2(10000, Val{3})

```

Timing results are

```julia
julia> @btime f1(10000, Val{3})
  2.647 ms (77422 allocations: 1.33 MiB)
50015000

julia> @btime f2(10000, Val{3})
  22.971 μs (0 allocations: 0 bytes)
50015000

```

Is there any way to create an NTuple performantly without resorting to generated functions?

---

<div class="post-metadata">

**Author:** ![tkoolen](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/tkoolen/32/1603_2.png) [@tkoolen](https://discourse.julialang.org/u/tkoolen)\
**Post date:** [September 8, 2017, 1:34pm UTC](https://discourse.julialang.org/t/performant-way-to-create-ntuple/5783/2 "2017-09-08T13:34:36Z")

</div>

This is [performance of captured variables in closures · Issue #15276 · JuliaLang/julia · GitHub](https://github.com/JuliaLang/julia/issues/15276). You can work around it [using a let block](https://github.com/JuliaLang/julia/issues/15276#issuecomment-297596373)

```julia
using BenchmarkTools
@noinline g(x) = x[1]

function f1(M, ::Type{Val{N}}) where N
    s = 0
    for j = 1:M
        let j = j
            x = ntuple(i -> i + j, Val{N})
            s += g(x)
        end
    end
    return s
end

```

---

<div class="post-metadata">

**Author:** ![GunnarFarneback](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/gunnarfarneback/32/1827_2.png) [@GunnarFarneback](https://discourse.julialang.org/u/GunnarFarneback)\
**Post date:** [September 8, 2017, 8:53pm UTC](https://discourse.julialang.org/t/performant-way-to-create-ntuple/5783/3 "2017-09-08T20:53:09Z")

</div>

Thanks. I’ve read that issue before but apparently not actively enough to make the connection. This solves my non-simplified problem as well. Great help.
