Often I need to “broadcast” the field of a given structure, e.g.:
struct Foo
id::Int64
end
mylist = [Foo(1),Foo(2),Foo(1)]
[e.id for e in mylist]
There is no way to broadcast the dot indicating field ownership, e.g. mylist..id
?
Often I need to “broadcast” the field of a given structure, e.g.:
struct Foo
id::Int64
end
mylist = [Foo(1),Foo(2),Foo(1)]
[e.id for e in mylist]
There is no way to broadcast the dot indicating field ownership, e.g. mylist..id
?
getproperty
is the function being called with the dot syntax, so you can broadcast that function directly:
julia> getproperty.(mylist, :id)
3-element Vector{Int64}:
1
2
1
The comprehension seems to be much more efficient than getproperty
(at least in Julia 1.7.2):
struct Foo
id::Int64
end
mylist = [Foo(rand(1:10)) for _ in 1:10_000]
f(mylist) = [e.id for e in mylist]
g(mylist) = getproperty.(mylist, :id)
@btime f($mylist) # 5.3 μs (2 allocs: 78 KiB)
@btime g($mylist) # 152 μs (10003 allocs: 234 KiB)