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

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