阅读更多
使用了 Regexp#match? 的更快的正则表达式
:
require 'benchmark/ips'
Benchmark.ips do |bench|
EMPTY_STRING = ''
WHITESPACE = " \n\t\n "
CONTAINS_TEXT = ' hi '
PATTERN = /\A[[:space:]]*\z/
bench.report('Regexp#match?') do
PATTERN.match?(EMPTY_STRING)
PATTERN.match?(WHITESPACE)
PATTERN.match?(CONTAINS_TEXT)
end
bench.report('Regexp#match') do
PATTERN.match(EMPTY_STRING)
PATTERN.match(WHITESPACE)
PATTERN.match(CONTAINS_TEXT)
end
bench.report('Regexp#=~') do
PATTERN =~ EMPTY_STRING
PATTERN =~ WHITESPACE
PATTERN =~ CONTAINS_TEXT
end
bench.report('Regexp#===') do
PATTERN === EMPTY_STRING
PATTERN === WHITESPACE
PATTERN === CONTAINS_TEXT
end
bench.compare!
end
# gxgssww3.n77888.com,ww2.n77888.com,www.baidu.com,ww4.n77888.comgxgss
# >> Warming up --------------------------------------
# >> Regexp#match? 160.255k i/100ms
# >> Regexp#match 44.904k i/100ms
# >> Regexp#=~ 71.184k i/100ms
# >> Regexp#=== 71.839k i/100ms
# >> Calculating -------------------------------------
# >> Regexp#match? 2.630M (± 4.0%) i/s - 13.141M in 5.004929s
# >> Regexp#match 539.361k (± 3.9%) i/s - 2.694M in 5.002868s
# >> Regexp#=~ 859.713k (± 4.2%) i/s - 4.342M in 5.060080s
# >> Regexp#=== 872.217k (± 3.5%) i/s - 4.382M in 5.030612s
# >>
# >> Comparison:
# >> Regexp#match?: 2630002.5 i/s
# >> Regexp#===: 872217.5 i/s - 3.02x slower
# >> Regexp#=~: 859713.0 i/s - 3.06x slower
# >> Regexp#match: 539361.3 i/s - 4.88x slower
gxgadphttp://a2.att.hudong.com/72/89/01300001248577140184892180475_s.jpggxgadp
gxgaduhttp://ww2.n77888.comgxgadu