`sort` vs `copy`+`sort!`

This is run on Julia 1.8.3

using BenchmarkTools

function benchsort(L)
    v = rand(L)
    @show L
    @btime sort($v)
    @btime sort!($v)
    @btime sort!(copy($v))
    nothing
end

Running this with 2048 length vectors (same results apply to any length):

julia> benchsort(2048)
L = 2048
  74.018 μs (1 allocation: 16.12 KiB)
  11.578 μs (0 allocations: 0 bytes)
  13.083 μs (1 allocation: 16.12 KiB)

Why is sort so much slower than sort! ? And should it be?

Sorting first checks if the data is already sorted, and return directly if so. In your example you sort the vector v in place with your first call to sort!, so the remaining calls will not do any sorting. You can use setup=(...) for cases like this (see BenchmarkTools.jl documentation):

julia> L = 2048; x = rand(L);

julia> @btime sort(v) setup=(v = copy(x)) evals=1;
  56.562 μs (1 allocation: 16.12 KiB)

julia> @btime sort!(v) setup=(v = copy(x)) evals=1;
  55.691 μs (0 allocations: 0 bytes)

julia> @btime sort!(copy(v)) setup=(v = copy(x)) evals=1;
  56.428 μs (1 allocation: 16.12 KiB)
6 Likes

Even this doesn’t seem fireproof. Shouldn’t it have evals=1, otherwise you may run into the same problem for the second case, for shorter vectors, for example.

6 Likes

You are correct, I updated the post above to include that.

1 Like