I create a vector of vectors as follows.
v = map(rand, fill(10^4, 5));
I want to compute a mean of all the elements in all 5 vectors, i.e. flattening the “v”. I approached this in the following three different ways.
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) for u ∈ v, x ∈ u a += x end a / sum(length, v) end
The timings indicate that flatMean_generator() and flatMean_flatten() are a lot slower with considerable number of allocations if compared to flatMean_explicitLoop().
@time getFlatMean_generator(v) # executed several times 0.001598 seconds (50.01 k allocations: 1.526 MiB) @time getFlatMean_flatten(v) 0.001641 seconds (50.01 k allocations: 1.526 MiB) @time getFlatMean_explicitLoop(v) 0.000216 seconds (5 allocations: 176 bytes)
Is this a known issue ? Generators with a single “for” keyword are in general as fast as an explicit loop.