Last active
January 26, 2016 04:56
-
-
Save southwolf/b6ae3c8ff82e959548ac to your computer and use it in GitHub Desktop.
ruby_precise_integer_validator
This file contains 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
require 'bigdecimal' | |
require 'benchmark' | |
def is_a_prcisely_integer?(raw_value) | |
BigDecimal.new(raw_value.to_s).frac == 0 | |
end | |
def is_a_literal_integer?(raw_value) | |
/\A[+-]?\d+(\.)?(?(1)0+\z|\z)/ === raw_value.to_s | |
end | |
def is_an_integer?(raw_value) | |
/\A[+-]?\d+\z/ === raw_value.to_s | |
end | |
n = 1000000 # 1 Million Times | |
Benchmark.bm do |x| | |
x.report("RegEx:") { for i in 1..n; is_an_integer?("1.0"); end } | |
x.report("Literal:") { for i in 1..n; is_a_literal_integer?("1.0"); end } | |
x.report("Decimal:") { for i in 1..n; is_a_prcisely_integer?("1.0"); end } | |
end | |
# user system total real | |
# RegEx: 0.700000 0.000000 0.700000 ( 0.719871) | |
# Literal: 1.720000 0.030000 1.750000 ( 1.974486) | |
# Decimal: 2.520000 0.040000 2.560000 ( 2.610777) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment