Skip to content

type instability when swapping two integers and feeding a sum #59230

@lmiq

Description

@lmiq

Probably a duplicate of some known issue, but anyway:

This is the MWE:

function unstable(x,k,l)
    if k > l; k, l = l, k; end
    return sum((x[k]+x[l])^2 for _ in eachindex(x)) 
end

function stable(x,k,l)
    k, l = if k > l; (l, k); else (k, l); end
    return sum((x[k]+x[l])^2 for _ in eachindex(x)) 
end
julia> @b unstable(1:100, 2, 10)
4.478 μs (299 allocs: 7.797 KiB)

julia> @b stable(1:100, 2, 10)
1.335 ns

(from: https://discourse.julialang.org/t/help-with-optimising-a-simple-function/131459/6)

Metadata

Metadata

Assignees

No one assigned

    Labels

    duplicateIndicates similar issues or pull requestsperformanceMust go faster

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions