Skip to content

Instantly share code, notes, and snippets.

@benmanns
Forked from anonymous/benchmark.rb
Created November 25, 2010 06:05
Show Gist options
  • Save benmanns/714980 to your computer and use it in GitHub Desktop.
Save benmanns/714980 to your computer and use it in GitHub Desktop.
require 'benchmark'
def benchmark(setting, &block)
data = (1..10_000_000).map { block.call }
Benchmark.bm(15) do |x|
x.report("compact #{setting}") do
data.dup.each do |d|
[d[0],d[1]].compact.min
end
end
x.report("ternary #{setting}") do
data.dup.each do |d|
d[0] ? [d[0],d[1]].min : d[1]
end
end
end
end
benchmark('exists'){ [rand,rand] }
benchmark('nil'){ [nil,rand] }
user system total real
compact exists 8.620000 0.690000 9.310000 ( 12.577204)
ternary exists 7.410000 0.230000 7.640000 ( 7.646824)
user system total real
compact nil 4.450000 0.020000 4.470000 ( 4.473185)
ternary nil 1.290000 0.000000 1.290000 ( 1.291536)
@benmanns
Copy link
Author

I expanded the sample size from 1,000 to 10,000,000, because comparing microseconds is just silly to me. With larger sample sizes we see a roughly 1.5:1 and 3.5:1 difference between compact and ternary.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment