Skip to content

Use Array#shuffle for random spec ordering

Created by: laserlemon

There's a big performance win in #shuffle over #sort_by that can be significant for large test suites.

require "benchmark"

ARRAY = (1..1_000).to_a

Benchmark.bmbm do |x|
  x.report("sort_by") do
    10_000.times do
      ARRAY.sort_by { Kernel.rand(ARRAY.size) }
    end
  end

  x.report("shuffle") do
    10_000.times do
      ARRAY.shuffle
    end
  end
end
Rehearsal -------------------------------------------
sort_by   8.360000   0.010000   8.370000 (  8.367450)
shuffle   0.350000   0.000000   0.350000 (  0.347621)
---------------------------------- total: 8.720000sec

              user     system      total        real
sort_by   8.370000   0.010000   8.380000 (  8.380927)
shuffle   0.310000   0.000000   0.310000 (  0.313796)

Merge request reports