Inspired by Zero-Cost Abstractions I tried to implement field based access for a dictionary. It kinda works, but could it be improved? Why isn’t the last function working as fast as it should? I’m using julia v1.0.3.
using BenchmarkTools
struct A{T}
__dict::Dict{Symbol, T}
end
a = A{Float64}(Dict(:x => 0.3))
f(a) = a.__dict[:x]
@btime f(a) # 19.032 ns (1 allocation: 16 bytes)
@inline @generated getter(a::A,::Val{s}) where s = :(getfield(a, :__dict)[s])
@inline Base.getproperty(a::A, s::Symbol) = getter(a, Val(s))
g(a) = a.x
@btime g(a) # 18.775 ns (1 allocation: 16 bytes)
@inline @generated getter(a::A,::Val{:__dict}) = :(getfield(a, :__dict))
h(a) = a.__dict
@btime h(a) # 10.469 ns (0 allocations: 0 bytes)
@inline @generated getter(a::A,::Val{s}) where s = :(a.__dict[s])
i(a) = a.x
@btime i(a) # 2.370 μs (1 allocation: 16 bytes)