Array confusion

Could someone explain this idiom please… I don’t know what is going on, despite seeing that the result makes sense.

julia> [5 for i in 1:3]
3-element Array{Int64,1}:
5
5
5

Thanks.

https://docs.julialang.org/en/latest/manual/arrays/#Comprehensions-1

2 Likes

AFAIK this is just a shorthand for a for loop:

x = Vector{Float64}(undef, 3)
for j in 1 : 3
  x[j] = 5
end

Whether there is a performance benefit is not clear to me.

Not really, it lowers into a collect call.

Besides the obvious syntactic advantages (it is shorter), you don’t have to calculate a container element type, and can also filter on the fly.

So I should expect the comprehension to be generically faster than the loop?

No (and I did not say this — please read what I said). It is not about speed per se.

When the compiler can infer types, you know the number of elements in advance, and you take the allocation of the result container into account, I would not expect a difference in speed.