Skip to content

Instantly share code, notes, and snippets.

@iamteem
Created April 27, 2010 01:44
Show Gist options
  • Save iamteem/380206 to your computer and use it in GitHub Desktop.
Save iamteem/380206 to your computer and use it in GitHub Desktop.
#!/usr/bin/env ruby -w
require 'benchmark'
n = 1_000_000
l = (1..n).to_a.shuffle
conditions = [
proc { |i| i > 5 },
proc { |i| (i % 2).zero? },
proc { |i| (i % 3).zero? },
proc { |i| i**2 - 2*i > i**1.5 }
]
Benchmark.bmbm do |x|
x.report("select") do
l.select { |i| i > 5 && (i % 6).zero? && i**2 - 2*i > i**1.5 }.join(', ')
end
x.report("select 2") do
l.select { |i| i > 5 && (i % 2).zero? && (i % 3).zero? && i**2 - 2*i > i**1.5 }.join(', ')
end
x.report("select-all?") do
l.select do |i|
conditions.all? { |c| c[i] }
end.join(', ')
end
x.report("inject-select") do
conditions.inject(l) {|a, e| a.select(&e) }.join(", ")
end
x.report("inject-inject") do
conditions.inject(l) {|a, e| a.inject([]) {|acc, el| e[el] ? acc << el : acc } }.join(", ")
end
end
__END__
Rehearsal -------------------------------------------------
select 0.800000 0.010000 0.810000 ( 0.806892)
select 2 0.860000 0.000000 0.860000 ( 0.869066)
select-all? 3.860000 0.010000 3.870000 ( 3.859497)
inject-select 1.070000 0.010000 1.080000 ( 1.082038)
inject-inject 1.850000 0.020000 1.870000 ( 1.876395)
---------------------------------------- total: 8.490000sec
user system total real
select 0.860000 0.000000 0.860000 ( 0.861155)
select 2 0.930000 0.000000 0.930000 ( 0.931503)
select-all? 4.310000 0.000000 4.310000 ( 4.309884)
inject-select 1.120000 0.020000 1.140000 ( 1.138431)
inject-inject 1.860000 0.020000 1.880000 ( 1.883042)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment