Is there any way to the get the efficient assignment of f1 with the nicer syntax of f2? Something like a view or conditional SubArray?
julia> function f1!(xs)
for i in eachindex(xs)
if xs[i] < 0.5
xs[i] = 0.0
end
end
end
f1! (generic function with 1 method)
julia> function f2!(xs)
xs[xs .< 0.5] .= 0.0
end
f2! (generic function with 1 method)
julia> v = rand(100);
julia> @btime f1!($v);
121.872 ns (0 allocations: 0 bytes)
julia> @btime f2!($v);
659.691 ns (3 allocations: 656 bytes)
julia> function f1!(xs)
@inbounds @simd for i in eachindex(xs)
if xs[i] < 0.5
xs[i] = 0.0
end
end
end
f1! (generic function with 1 method)
julia> @btime f1!(v) setup=(v=rand(10^4))
961.094 ns (0 allocations: 0 bytes)
On my computer this is equivalent to h! above of @DNF.