# Best practices with ComponentArrays.jl

**URL:** <https://discourse.julialang.org/t/best-practices-with-componentarrays-jl/66064>\
**Category:** General Usage\
**Tags:** componentarrays\
**Created:** [August 9, 2021, 7:54am UTC](https://discourse.julialang.org/t/best-practices-with-componentarrays-jl/66064 "2021-08-09T07:54:08Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![amrods](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/amrods/32/2543_2.png) [@amrods](https://discourse.julialang.org/u/amrods)\
**Post date:** [August 9, 2021, 7:54am UTC](https://discourse.julialang.org/t/best-practices-with-componentarrays-jl/66064/1 "2021-08-09T07:54:08Z")

</div>

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).

```julia
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

```

---

<div class="post-metadata">

**Author:** ![jonniedie](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/jonniedie/32/12842_2.png) [@jonniedie](https://discourse.julialang.org/u/jonniedie)\
**Post date:** [August 19, 2021, 7:26pm UTC](https://discourse.julialang.org/t/best-practices-with-componentarrays-jl/66064/2 "2021-08-19T19:26:05Z")

</div>

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.
