struct Point
x :: Int
y :: Int
end
a
タイプの配列がある場合Array{Point}
、これよりもフィールドアクセスを行うためのより良い方法(構文的にクリーンまたは高速)はありますか?
(p->p.x).(a)
最もクリーンな方法は、@ pabloferzによってDiscourseに最初に投稿された独自の演算子を定義することです:https://discourse.julialang.org/t/broadcast-over-getfield-in-0-6/2335/4
struct Point
x :: Int
y :: Int
end
a = [Point(i,j) for i = 1:10 for j = 1:10]
↦(val, s) = getfield(val, s)
a .↦ :x
a .↦ :y
今のところ、小さい(p->p.x).(a)
場合、他のソリューションの中でクイックベンチマークショーが最速a
です。長さは、時にa
大きな成長し、両方map
とcomprehension
わずかに速くよります(p->p.x).(a)
:
julia> versioninfo()
Julia Version 0.6.0
Commit 903644385b* (2017-06-19 13:05 UTC)
......
julia> @btime (p->p.x).($a)
88.283 ns (1 allocation: 896 bytes)
julia> @btime [ z.x for z in $a ]
109.578 ns (2 allocations: 912 bytes)
julia> @btime map(p->p.x, $a)
163.485 ns (3 allocations: 944 bytes)
julia> @btime getfield.($a,:x)
1.586 μs (101 allocations: 4.00 KiB)
julia> a = [Point(i,j) for i = 1:100 for j = 1:100]
julia> @btime getfield.($a,:x);
160.845 μs (10002 allocations: 390.70 KiB)
julia> @btime (p->p.x).($a);
9.817 μs (2 allocations: 78.20 KiB)
julia> @btime map(p->p.x, $a);
8.306 μs (3 allocations: 78.22 KiB)
julia> @btime [ z.x for z in $a ];
8.306 μs (3 allocations: 78.22 KiB)
getfield
は常に他の方法よりも10〜20倍遅いため、最もクリーンな方法はパフォーマンスが高くありません。しかし、状況は将来改善されると思われますMake .a syntactic sugar for i->i.a #22710
。これには構文糖衣構文がありますか?:。
この記事はインターネットから収集されたものであり、転載の際にはソースを示してください。
侵害の場合は、連絡してください[email protected]
コメントを追加