What's the best way to create a struct of arrays?

I have another question which is about what is the best way to create structs.

struct s1{V1<:AbstractVector, V2<:AbstractVector{Int}}
    X1::V1
    X2::V1
    X3::V1
    State::V2
end

or

struct s2{T1}
    X1::Vector{T1}
    X2::Vector{T1}
    X3::Vector{T1}
    State::Vector{Int}
end

Hey @hssn15, I’ve split this secondary question out into its own topic.

Fundamentally, both will be able to perform exactly the same and have some similar behaviors, but which is best will depend on your use case:

  • s1 can support many array types (e.g., sparse, bitarray, etc., etc.). s2 only supports Vector.
  • s2{T} allows you to more easily introspect (and dispatch on) the element types of X1, X2, X3. s1{V} would allow more simple dispatch on the array types.

Thank you for your reply. It was very helpful.

What about in terms of speed. In my case both can be used. But, I would like to choose faster version.

Thank You.

To be even more concrete, the performance (and even the memory layout) of s1{Vector{Float64}, Vector{Int}} will be identical to the performance of s2{Float64}.

1 Like

You should check out StructArrays.jl, which stores things as a struct-of-arrays but also provides convenient access as if they were arrays-of-structs.

1 Like