Skip to content

Instantly share code, notes, and snippets.

@tenderlove
Created January 12, 2012 00:43
Show Gist options
  • Save tenderlove/1597744 to your computer and use it in GitHub Desktop.
Save tenderlove/1597744 to your computer and use it in GitHub Desktop.
# encoding: utf-8
require 'rubygems'
require 'benchmark/ips'
require 'set'
TRUE_VALUES = [true, 1, '1', 't', 'T', 'true', 'TRUE'].to_set
def original value
if value.is_a?(String) && value.empty?
nil
else
TRUE_VALUES.include?(value)
end
end
def regexp value
case value
when String
value =~ /^(?:1|t(?:rue)?)$/i
when true, 1
true
else
false
end
end
n = 50000
Benchmark.ips do |x|
x.report('original hit') {
original 'true'
}
x.report('original miss') {
original 'false'
}
x.report('regex hit') {
regexp 'true'
}
x.report('regex miss') {
regexp 'false'
}
end
__END__
$ ruby test.rb
original hit 345653.8 (±18.7%) i/s - 1641500 in 4.997906s (cycle=9380)
original miss 357417.3 (±18.5%) i/s - 1707888 in 5.022346s (cycle=9384)
regex hit 256663.3 (±27.8%) i/s - 1142302 in 5.040709s (cycle=8218)
regex miss 349140.4 (±18.6%) i/s - 1665416 in 5.009205s (cycle=9304)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment