Hello, I have the following technical question: when using - as prefix operator, does it get broadcasted as it would be an operator with a dot, i.e. is this
x = 2
y = [1,2,3]
z = -x .+ y
equivalent to
x = 2
y = [1,2,3]
z = -1 .* x .+ y
because it would matter in terms of performance.
At least the @code_lowered after defining a function is not the same:
julia> f(x,y) = .-x .+ y
f (generic function with 1 method)
julia> g(x,y) = -1 .* x .+ y
g (generic function with 1 method)
julia> @btime f($x,$y)
39.354 ns (1 allocation: 112 bytes)
3-element Array{Int64,1}:
-3
-3
-3
julia> @btime g($x,$y)
39.315 ns (1 allocation: 112 bytes)
3-element Array{Int64,1}:
-3
-3
-3
The reason it’s gotten slower if you don’t dot it as well is because if an expression has all dots, the compiler can fuse all the broadcasts into a single call, greatly reducing overhead. The same can be achieved with @. which dots every operator/function call:
julia> h(x,y) = @. -x + y
h (generic function with 1 method)
julia> @btime h($x,$y)
39.315 ns (1 allocation: 112 bytes)
3-element Array{Int64,1}:
-3
-3
-3
Yes, I know, just did not realiesed that using .- is the right way for writing it, because usually for a function you use f.() so I thougt it should be -.x.