public
Last active

  • Download Gist
test.rb
Ruby
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52
# 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)

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.