Are Julia arrays homogeneous or not?

Viewed 141

On the one hand, if I have x=[1,2,3], then I cannot add "foo" to x, but if I start with x=[1,2,3,"foo"], then the union type is Any, and I can add whatever I want to my array. Is it correct to say that Julia arrays are homogeneous? Because I can just create array of Any.

1 Answers

Julia will by default restrict a given array to as specific an element type (eltype) as possible. However, julia has a special syntax to make an array with whatever eltype you like. So, to create an array with eltype T, you just write T[x, y, z] instead of [x, y, z]. For your example, this would be

julia> v = Any[1,2,3]
p3-element Array{Any,1}:
 1
 2
 3

julia> push!(v, "foo")
4-element Array{Any,1}:
 1
 2
 3
  "foo"

The reason for this behaviour is that if we can restrict an array to be of a specific, concrete type, there are some major performance optimizations that can be made. If you have an array with eltype Any, then the contents cannot be densely packed in memory.

Related