Skip to content

Instantly share code, notes, and snippets.

@amcaplan
Created September 5, 2021 18:24
Show Gist options
  • Save amcaplan/b5cea4d19b490685bd511417654d6601 to your computer and use it in GitHub Desktop.
Save amcaplan/b5cea4d19b490685bd511417654d6601 to your computer and use it in GitHub Desktop.
Surprising Ruby benchmark results for Array#unshift: 2.5.9 vs 2.6.0
Warming up --------------------------------------
Array#unshift 1.000 i/100ms
Array#push 16.000 i/100ms
Calculating -------------------------------------
Array#unshift 0.428 (± 0.0%) i/s - 3.000 in 7.014513s
Array#push 178.573 (± 9.0%) i/s - 896.000 in 5.064291s
Comparison:
Array#push: 178.6 i/s
Array#unshift: 0.4 i/s - 417.41x (± 0.00) slower
Warming up --------------------------------------
Array#unshift 17.000 i/100ms
Array#push 19.000 i/100ms
Calculating -------------------------------------
Array#unshift 181.828 (± 6.6%) i/s - 918.000 in 5.076970s
Array#push 187.124 (± 8.0%) i/s - 931.000 in 5.011387s
Comparison:
Array#push: 187.1 i/s
Array#unshift: 181.8 i/s - same-ish: difference falls within error
require 'benchmark/ips'
Benchmark.ips do |x|
x.report('Array#unshift') do
array = (1..100).to_a
100_000.times { |i| array.unshift(i) }
end
x.report('Array#push') do
array = (1..100).to_a
100_000.times { |i| array.push(i) }
end
x.compare!
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment