如果我有一个命令y = A*B*x
,其中A
&B
是大矩阵而x
&y
是向量,Julia 会预成型y = ((A*B)*x)
还是y = (A*(B*x))
?
第二个选项应该是最好的,因为它只需要分配一个额外的向量而不是一个大矩阵。
验证这种事情的最好方法是通过@code_lowered
宏转储降低的代码:
julia> @code_lowered A * B * x
CodeInfo(:(begin
nothing
return (Core._apply)(Base.afoldl, (Core.tuple)(Base.*, (a * b) * c), xs)
end))
Run Code Online (Sandbox Code Playgroud)
与许多其他语言一样,Julia 使用y = (A*B)*x
代替y = A*(B*x)
,因此您可以明确使用括号来减少分配。
julia> using BenchmarkTools
julia> @btime $A * ($B * $x);
6.800 ?s (2 allocations: 1.75 KiB)
julia> @btime $A * $B * $x;
45.453 ?s (3 allocations: 79.08 KiB)
Run Code Online (Sandbox Code Playgroud)