Is there a performance benefit of writing “getter” functions for structs in Julia? For example, let’s say I define a struct and a “get” function for its field:
struct Foo
bar
end
function get_bar(foo::Foo)
return foo.bar
end
foo = Foo(1)
Is there any performance benefit from using get_bar as opposed to directly accessing the field such as in foo.bar?
Not generally, no; property access is already quite optimal. What makes it fast is that something like foo.bar is lowered to getproperty(foo, :bar), where that :bar is a constant Symbol. This is very easy to propagate into getproperty as a constant, so it’s not beneficial to further wrap that in another function call, as the two would fundamentally do & rely on the same thing to be fast.
One reason many packages use getter functions is to make interfaces a bit more explicit.
For example the fields of structs are often considered to be internals that could be renamed, or depend on the specific instance of the subtype, while one can instead export a getter function which simply accesses a field.
For example something like
struct ArrayWrap <: AbstractArray
parent:: AbstractVector{Float64}
end
Base.parent(A::ArrayWrap) = A.parent
struct ArrayWrap2 <: AbstractArray
data:: AbstractVector{Float64}
end
Base.parent(A::ArrayWrap2) = A.data
function doSomething(vec::AbstracArray)
par = parent(vec)
...
end
is quite commonly used, and does not require every wrapper of an array to give the parent array the same name, they just need to export the appropriate parent function.
But this has nothing to do with performance as correctly said in the post above. Both versions will be compiled to the same