Vector operations: any preference for using AbstractVector or n-by-1 array

Consider the multiplication of a n-by-n matrix M and a n-dimensional vector v, M*v. One may write v either

  • as an n-element Array (typeof(v) <: AbstractVector is true),
  • or write it as an n×1 array (typeof(v) <: AbstractVector is false).

Glancing through the source code matmul.jl, it looks like one uses gemv! and the other uses gemm_wrapper!; as for timing, there seems to be very small differences


@btime $m*$v;
  34.902 ms (2 allocations: 78.20 KiB)

@btime $m*$v2;
  36.459 ms (2 allocations: 78.20 KiB)

Also, to make an n-by-n matrix from v*v', @which shows Vector uses adjtrans.jl while n-by-1 array uses matmul.jl. Looks like AbstractVector can be slightly faster for high dimension cases, and for things like v'*m*v, typeof(v) <: AbstractVector gives a number whereas n-by-1 matrix v gives a 1-by-1 matrix.
Generally, what’s the pros/cons of using one as opposed to the other, and is there any preferences for using either one?


In my opinion, you are taking too fine-grained a perspective. Keep it simple.
typeof(zeros(Int, 3)) == Array{Int64,1}, so do what Julia does: use an n-element Array. That way, whatever you do likely works with other sorts of AbstractVector – which is very helpful.

1 Like

This is very related to a very (in)famous Julia issue:

(Warning: it’s also one of the longest Julia issues…)

1 Like

To summarize: Use a 1-dimensional Vector if you mean a vector.