Skip to content

Instantly share code, notes, and snippets.

@edbond
Last active December 19, 2015 15:08
Show Gist options
  • Select an option

  • Save edbond/5973925 to your computer and use it in GitHub Desktop.

Select an option

Save edbond/5973925 to your computer and use it in GitHub Desktop.
Regexp vs Exceptions for IPAddr validation
require 'ipaddr'
def by_exception ip
begin
IPAddr.new(ip, Socket::AF_INET)
true
rescue ArgumentError
false
end
end
def by_regexp ip
!!ip.match(/\A(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\Z/)
end
# First some sanity checks
{
"355.55.43.33" => false,
"245.34.63.44" => true,
"10.10.90.424" => false,
"127.0.0.1" => true,
}.each do |ip, result|
raise "Doesn't pass sanity check, by_exception(#{ip}) == #{result}" unless by_exception(ip) == result
raise "Doesn't pass sanity check, by_regexp(#{ip}) == #{result}" unless by_regexp(ip) == result
end
N = 100_000
Benchmark.bm(20) do |x|
x.report("Regexp FAIL") { N.times { by_regexp("355.55.43.43") } }
x.report("Exception FAIL") { N.times { by_exception("355.55.43.43") } }
x.report("Regexp OK") { N.times { by_regexp("10.10.0.1") } }
x.report("Exception OK") { N.times { by_exception("10.10.0.1") } }
end
## RESULTS ruby 1.8.7 (2012-10-12 patchlevel 371) [x86_64-linux]
user system total real
Regexp FAIL 0.110000 0.000000 0.110000 ( 0.108501)
Exception FAIL 12.300000 16.160000 28.460000 ( 37.298097)
Regexp OK 0.210000 0.000000 0.210000 ( 0.212452)
Exception OK 1.730000 0.000000 1.730000 ( 1.732759)
## RESULTS ruby 1.9.2p320 (2012-04-20 revision 35421) [x86_64-linux]
user system total real
Regexp FAIL 0.080000 0.000000 0.080000 ( 0.080491)
Exception FAIL 14.550000 16.210000 30.760000 ( 39.894375)
Regexp OK 0.140000 0.000000 0.140000 ( 0.151422)
Exception OK 0.810000 0.000000 0.810000 ( 0.796678)
## RESULTS ruby 1.9.3p392 (2013-02-22 revision 39386) [x86_64-linux]
user system total real
Regexp FAIL 0.090000 0.000000 0.090000 ( 0.087240)
Exception FAIL 1.780000 0.010000 1.790000 ( 1.791048)
Regexp OK 0.160000 0.000000 0.160000 ( 0.161234)
Exception OK 0.840000 0.000000 0.840000 ( 0.849894)
## RESULTS ruby 2.0.0p0 (2013-02-24 revision 39474) [x86_64-linux]
user system total real
Regexp FAIL 0.090000 0.000000 0.090000 ( 0.092935)
Exception FAIL 0.890000 0.000000 0.890000 ( 0.893954)
Regexp OK 0.170000 0.000000 0.170000 ( 0.170380)
Exception OK 0.970000 0.000000 0.970000 ( 0.968676)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment