Semantically equivalent expressions with wildly different performance

bremez
Mon, 28 Jul 2025 04:40:52 +0000
General Usage

I came across the following example when I needed something that beats the performance of LinearAlgebra’s build in mul!(M, x, y'). Any known reason for this huge difference in performance? Tested on 11.6.

using BenchmarkTools
function outer1!(output, x, y)
    for j in eachindex(y)
        @. (view(output, :, j)) = x *  y[j]
    end
    return output
end

function outer2!(output, x, y)
    for j in eachindex(y)
        v = view(output, :, j)
        @. (v) = x *  y[j]
    end
    return output
end

x = rand(1000); y = rand(1000); M = rand(1000,1000);
outer1!(M, x, y) ≈   outer2!(M, x, y)
#true

@btime outer1!(M, x, y);
# ~10 ns
@btime outer2!(M, x, y);
# ~200 μs

11 posts - 4 participants