# How to use \`@generated\` to eliminate a for loop?

**URL:** <https://discourse.julialang.org/t/how-to-use-generated-to-eliminate-a-for-loop/103915>\
**Category:** General Usage\
**Tags:** metaprogramming\
**Created:** [September 15, 2023, 7:58pm UTC](https://discourse.julialang.org/t/how-to-use-generated-to-eliminate-a-for-loop/103915 "2023-09-15T19:58:29Z")\
**Posts on this page:** 1\
**Showing post:** 2

<div class="post-metadata">

**Author:** ![ffevotte](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/ffevotte/32/6587_2.png) [@ffevotte](https://discourse.julialang.org/u/ffevotte)\
**Post date:** [September 15, 2023, 9:19pm UTC](https://discourse.julialang.org/t/how-to-use-generated-to-eliminate-a-for-loop/103915/2 "2023-09-15T21:19:07Z")

</div>

> [@mihalybaci](#):
>
> I could not find a way to pass the size of the third dimension of the array into `@generated` in order write the correct number of additions, so I used a giant hack to create an `Tuple` of the correct length `N`, which does get passed.

I’d say the most standard way to lift a value to the type domain would be to use `Val`

Also, there would be ways to write your `@generated` function so that is manipulates expressions rather than strings (which would remove the need for `Meta.parse`), but I don’t think it’s really necessary to use a `@generated` function here.

I’d for example rather use `NTuple`s, for which the compiler can often generate very optimized code in which loops have been unrolled:

```julia
julia> x = rand(1000, 1000, 4);

julia> my_matrix_sum(x) = @views @. x[:,:,1] + x[:,:,2] + x[:,:,3] + x[:,:,4]
my_matrix_sum (generic function with 1 method)

julia> using BenchmarkTools
julia> ref = my_matrix_sum(x);
julia> @btime my_matrix_sum($x);
  1.245 ms (2 allocations: 7.63 MiB)

```

```julia
julia> my_matrix_sum2(x) = my_matrix_sum2(x, Val(size(x, 3)));
       function my_matrix_sum2(x, N::Val)
           t = ntuple(N) do i
               @view x[:,:,i]
           end
           (+).(t...)
       end
my_matrix_sum2 (generic function with 2 methods)

julia> @assert ref == my_matrix_sum2(x);
julia> @btime my_matrix_sum2($x);
  1.252 ms (2 allocations: 7.63 MiB)

```

---

_[View the full topic](https://discourse.julialang.org/t/how-to-use-generated-to-eliminate-a-for-loop/103915)._
