Efficient design for library of objects

Hello,

I’m trying to make a library of user-constructed mutable structs which I can quickly search through, extract values from, and add new structs to. The most obvious design to me is to put each struct object into an array.

Is there an efficient way to search through a specific field of each object in the array? Alternatively I am wondering if it would be more sensible (and faster) to replace the array single struct where the fields are arrays of values from each struct? Or perhaps dictionaries would be helpful?

Thanks in advance.

Searching through a specific field can be done with findfirst()/findlast()/findall():

# finds all indices of A where A[i].fieldname == 5
findall(x->x.fieldname==5, A)

# a wrapper for convenience
function findfield(predicate::Function, A::AbstractArray, name::Symbol) 
    findall(x->predicate(getfield(x, name)), A)
end

Your second question is the classic “array of structs vs. struct of arrays” dilemma. Depending on the use patterns, one or the other might be better. SoA is more cache- and SIMD-friendly if you only want to process one field at a time. AoS is better when multiple fields have to be processed at once. AoS also makes algorithms like sorting much easier to write.

That’s very helpful, thank you!