A generator with two "for" keywords is slow

Sorry for unintentional changing of the function names. The following should work out of the box.

# Three different approaches to flattening of a vector of vectors.
flatMean_Generator(v) = mean( x for u ∈ v for x ∈ u )
flatMean_Flatten(v) = mean(Iterators.flatten(v))
            
function flatMean_ExplicitLoop(v)
    a = zero(v[1][1])
    
    for u ∈ v, x ∈ u
        a += x
    end
    
    a / sum(length, v)
end

# The data, a vector of 5 vectors of length 10^4.
v = map(rand, fill(10^4, 5))

Using @btime gives the following.

@btime flatMean_Generator(v)
723.562 μs (62314 allocations: 1.90 MiB)

0.4983977752093445

@btime flatMean_Flatten(v)
639.019 μs (62308 allocations: 1.90 MiB)

0.4983977752093445

@btime flatMean_ExplicitLoop(v)
64.727 μs (1 allocation: 16 bytes)

0.4983977752093445

The difference between the first two functions and explicit loop is about 10x.

Thanks.
Jan

p.s. The way the timing is done should be OK as @time or @btime is benchmarking what is happening inside, e.g., flatMean_Generator(v). The fact that “v” is from a global scope should be OK too. Correct me if I am wrong.