-
-
Save solnic/1600001 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# encoding: utf-8 | |
require 'rubygems' | |
require 'benchmark/ips' | |
require 'set' | |
TRUE_VALUES = [true, 1, '1', 't', 'T', 'true', 'TRUE'].to_set | |
BOOLEAN_MAP = Hash[ %w[ 1 on t true y yes ].product([ true ]) ] | |
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 | |
def boolean_map(value) | |
BOOLEAN_MAP.fetch(value.downcase, value) | |
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' | |
} | |
x.report('boolean_map hit') { | |
original 'TrUE' | |
} | |
x.report('boolean_map miss') { | |
original 'FaLSE' | |
} | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment