# Reducing getfield overhead?

**URL:** <https://discourse.julialang.org/t/reducing-getfield-overhead/113585>\
**Category:** General Usage\
**Created:** [April 28, 2024, 12:46pm UTC](https://discourse.julialang.org/t/reducing-getfield-overhead/113585 "2024-04-28T12:46:05Z")\
**Posts on this page:** 3\
**Page:** 1

<div class="post-metadata">

**Author:** ![vavrines](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/vavrines/32/8024_2.png) [@vavrines](https://discourse.julialang.org/u/vavrines)\
**Post date:** [April 28, 2024, 12:46pm UTC](https://discourse.julialang.org/t/reducing-getfield-overhead/113585/1 "2024-04-28T12:46:05Z")

</div>

A MWE:

```julia
using BenchmarkTools

struct Get_Field_Test
    x::Vector{Float64}
    y::Vector{Float64}
end

ts = Vector{Get_Field_Test}(undef, 1000)
for i in 1:1000
    ts[i] = Get_Field_Test(rand(100), rand(100))
end

function test1(ts)
    for i in 1:1000
        @inbounds ts[i].x .+= ts[i].y
    end
end
function test2(ts)
    for i in 1:1000
        for j = 1:100
            @inbounds ts[i].x[j] += ts[i].y[j]
        end
    end
end

@btime test1($ts)

@btime test2($ts)

```

The testing results

```julia
31.250 μs (0 allocations: 0 bytes)
105.769 μs (0 allocations: 0 bytes)

```

The overhead of the second test is annoying. I’m wondering if there’s a way to lower it?

---

<div class="post-metadata">

**Author:** ![bertschi](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/bertschi/32/33462_2.png) [@bertschi](https://discourse.julialang.org/u/bertschi)\
**Post date:** [April 28, 2024, 1:17pm UTC](https://discourse.julialang.org/t/reducing-getfield-overhead/113585/2 "2024-04-28T13:17:00Z")

</div>

> [@vavrines](#):
>
> The overhead of the second test is annoying. I’m wondering if there’s a way to lower it?

By eliminating common subexpressions:

```julia
function test3(ts)
    for i in 1:1000
        let tsix = ts[i].x, tsiy = ts[i].y
            for j = 1:100
                @inbounds tsix[j] += tsiy[j]
            end
        end
    end
end

```

But this is essentially the same the `test1` anyways.

---

<div class="post-metadata">

**Author:** ![Elrod](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/elrod/32/22461_2.png) [@Elrod](https://discourse.julialang.org/u/Elrod)\
**Post date:** [April 28, 2024, 8:51pm UTC](https://discourse.julialang.org/t/reducing-getfield-overhead/113585/3 "2024-04-28T20:51:08Z")

</div>

The loads `ts[i].x` and `ts[i].y` get hoisted out of the loop, but not the checks vs `nullptr`. That is, the `isassigned` check for throwing a `UndefRefError` is the problem.
