Sorting a vector of fixed size

One approach is to use SVectors from StaticArrays.jl:

1.7.0-rc1> using BenchmarkTools, StaticArrays

1.7.0-rc1> @benchmark sort(v) setup=(v=rand(8))  # ordinary vectors
BenchmarkTools.Trial: 10000 samples with 988 evaluations.
 Range (min … max):  47.773 ns … 675.911 ns  ┊ GC (min … max): 0.00% … 90.25%
 Time  (median):     55.466 ns               ┊ GC (median):    0.00%
 Time  (mean ± σ):   59.278 ns ±  22.770 ns  ┊ GC (mean ± σ):  1.54% ±  4.36%

   ▃▅▆▇██▇▆▃▁                                                  ▂
  ▇██████████▇▆▅▆▇▆▅▆▄▆▅▅▂▃▅▃▅▆▆█▇▇▇▆▅▆▆▆▅▆▅▆▆▇▇▇██▇▇▅▆▆▅▆▆▅▅▅ █
  47.8 ns       Histogram: log(frequency) by time       125 ns <

 Memory estimate: 128 bytes, allocs estimate: 1.

1.7.0-rc1> @benchmark sort(v) setup=(v=@SVector rand(8))  # static vectors
BenchmarkTools.Trial: 10000 samples with 996 evaluations.
 Range (min … max):  21.586 ns … 256.124 ns  ┊ GC (min … max): 0.00% … 0.00%
 Time  (median):     23.293 ns               ┊ GC (median):    0.00%
 Time  (mean ± σ):   24.495 ns ±   6.133 ns  ┊ GC (mean ± σ):  0.00% ± 0.00%

  ▇▃▇█▂▁▂▁▁▂▂▁▁▄▁▂                                             ▂
  ████████████████▄▅▅▅▅▅▅▅▅▆▆▅▄▅▆▆▆▅▇▆▆▆▆▇▆▆▆▅▆▅▆▅▆▆▅▅▄▃▃▅▄▄▁▅ █
  21.6 ns       Histogram: log(frequency) by time      55.2 ns <

 Memory estimate: 0 bytes, allocs estimate: 0.

It’s pretty fast, but the speedup is less than what you will see from other operations, probably.

SVectors are statically sized as well as immutable, if you absolutely have to mutate the vectors, there are also MVector, but in most cases immutability is not a problem.

2 Likes