Best practices with ComponentArrays.jl

Suppose I have a model M with parameters θ that are arranged in a ComponentArray. Model M has several components M1 to M2 that each take a subset of components of θ. I’m wondering what’s better, balancing performance and code organization/readability, of the options below (this is toy example, but suppose that all functions are costly).

using ComponentArrays
using UnPack

θ = ComponentArray{Float64}(θ1 = rand(1000), θ2 = rand(500))

function F(m1, m2)
    m1 + m2
end

## Option A

function AM1(θ1)
    prod(θ1)
end

function AM2(θ2)
    prod(sin.(θ2))
end

function AM(θ)
    @unpack θ1, θ2 = θ
    m1 = AM1(θ1)
    m2 = AM2(θ2)
    F(m1, m2)
end

## Option B

function BM1(θ)
    @unpack θ1 = θ
    prod(θ1)
end

function BM2(θ)
    @unpack θ2 = θ
    prod(sin.(θ2))
end

function BM(θ)
    m1 = BM1(θ)
    m2 = BM2(θ)
    F(m1, m2)
end

Performance-wise, it probably doesn’t matter much. I think the first version is almost always better for organization, though. That way M1 and M2 are separate unit-testable functions that don’t need to care about what the outer organization of the θ structure looks like. Or, to put it another way, M is the outer function that should be in responsible for sending its inner components to where they need to go. M1 and M2 shouldn’t have to know anything about the outer structure of θ–that’s M’s job.

2 Likes