Skip to content

Instantly share code, notes, and snippets.

@Nemo157
Created June 22, 2011 01:36
Show Gist options
  • Save Nemo157/1039348 to your computer and use it in GitHub Desktop.
Save Nemo157/1039348 to your computer and use it in GitHub Desktop.
require 'benchmark'
array = [*(1..9)] * 1_000_000
Benchmark.bmbm do |bm|
bm.report "with if" do
array.each_with_index do |element, i|
next if i == 1
element - 1
end
end
bm.report "without if" do
array.each do |element|
element - 1
end
end
bm.report "with reject" do
array.each_with_index.reject {|el,i| i == 1}.each do |el, i|
el- 1
end
end
bm.report "with first and drop" do
n = 1
(array.first(n) + array.drop(n + 1)).each do |el|
el- 1
end
end
bm.report "with ranges" do
n = 1
((0...n).to_a + ((n+1)...array.size).to_a).map{|i| array[i]}.each do |el|
el - 1
end
end
end
→ ruby -v bench.rb
ruby 1.9.2p180 (2011-02-18 revision 30909) [x86_64-darwin10.6.0]
Rehearsal -------------------------------------------------------
with if 1.830000 0.010000 1.840000 ( 1.847044)
without if 1.230000 0.000000 1.230000 ( 1.244233)
with reject 5.730000 1.720000 7.450000 ( 11.672952)
with first and drop 1.290000 0.060000 1.350000 ( 1.694164)
with ranges 3.880000 0.390000 4.270000 ( 4.543618)
--------------------------------------------- total: 16.140000sec
user system total real
with if 1.830000 0.000000 1.830000 ( 1.832242)
without if 1.230000 0.000000 1.230000 ( 1.239936)
with reject 5.040000 0.340000 5.380000 ( 5.428142)
with first and drop 1.270000 0.010000 1.280000 ( 1.292207)
with ranges 3.580000 0.190000 3.770000 ( 3.802674)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment