Is there a difference between Array
and Vector
?
typeof(Array([1,2,3]))
Vector{Int64}
typeof(Vector([1,2,3]))
Vector{Int64}
Both seem to create the same thing, but they are not the same:
Array == Vector
false
Array === Vector
false
So, what is actually the difference?
The length of an array is fixed once it is created, and elements cannot be added or removed before its creation. A Vector is a resizable-array that works by reallocating storage and copying the old array elements to a new array. A Vector is synchronized, whereas an array is not synchronized.
Vector is better for frequent insertion and deletion, whereas Arrays are much better suited for frequent access of elements scenario. Vector occupies much more memory in exchange for managing storage and growing dynamically, whereas Arrays are a memory-efficient data structure.
The difference is that Vector
is a 1-dimensional Array
, so when you write e.g. Vector{Int}
it is a shorthand to Array{Int, 1}
:
julia> Vector{Int}
Array{Int64,1}
When you call constructors Array([1,2,3])
and Vector([1,2,3])
they internally get translated to the same call Array{Int,1}([1,2,3])
as you passed a vector to them.
You would see the difference if you wanted to pass an array that is not 1-dimensional:
julia> Array(ones(2,2))
2×2 Array{Float64,2}:
1.0 1.0
1.0 1.0
julia> Vector(ones(2,2))
ERROR: MethodError: no method matching Array{T,1} where T(::Array{Float64,2})
Also note the effect of:
julia> x=[1,2,3]
3-element Array{Int64,1}:
1
2
3
julia> Vector(x)
3-element Array{Int64,1}:
1
2
3
julia> Vector(x) === x
false
So essentially the call Vector(x)
makes a copy of x
. Usually in the code you would probably simply write copy(x)
.
A general rule is that Array
is a parametric type that has two parameters given in curly braces:
eltype
)ndims
)See https://docs.julialang.org/en/v1/manual/arrays/ for details.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With