Difference between `A[:]` and `vec(A)`

julia> A, B = ones(3,), ones(3,);
julia> fn!(x) = begin x.=2 end;
julia> fn!(vec(A)); A
3×1 Array{Float64,2}:
 2.0
 2.0
 2.0
julia> fn!(B[:]); B
3×1 Array{Float64,2}:
 1.0
 1.0
 1.0

vec’s behaviour is understood from the doc.

I wonder if [:]'s behavior is expected, since the Performance Tips:

This can be verified using the vec function or the syntax [:] as shown below.

seems to suggest they should be indifferent.

Also, does this mean vec is more efficient than [:]?

2 Likes

Yes, this is expected. Square-bracketed indexing creates copies.

4 Likes

Note that if you use the @views macro, the result is what you were expecting (since there is no copy made):

julia> @views fn!(B[:]); B
3-element Array{Float64,1}:
 2.0
 2.0
 2.0
2 Likes