本文共 1334 字,大约阅读时间需要 4 分钟。
使用了 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) endbench.report('Regexp#match') do
PATTERN.match(EMPTY_STRING) PATTERN.match(WHITESPACE) PATTERN.match(CONTAINS_TEXT) endbench.report('Regexp#=~') do
PATTERN =~ EMPTY_STRING PATTERN =~ WHITESPACE PATTERN =~ CONTAINS_TEXT endbench.report('Regexp#===') do
PATTERN === EMPTY_STRING PATTERN === WHITESPACE PATTERN === CONTAINS_TEXT endbench.compare!
endWarming up --------------------------------------
Regexp#match? 160.255k i/100msRegexp#match 44.904k i/100msRegexp#=~ 71.184k i/100msRegexp#=== 71.839k i/100msCalculating -------------------------------------Regexp#match? 2.630M (± 4.0%) i/s - 13.141M in 5.004929sRegexp#match 539.361k (± 3.9%) i/s - 2.694M in 5.002868sRegexp#=~ 859.713k (± 4.2%) i/s - 4.342M in 5.060080sRegexp#=== 872.217k (± 3.5%) i/s - 4.382M in 5.030612sComparison:
Regexp#match?: 2630002.5 i/sRegexp#===: 872217.5 i/s - 3.02x slowerRegexp#=~: 859713.0 i/s - 3.06x slowerRegexp#match: 539361.3 i/s - 4.88x slowerzxdzhttp://huawen168.bokee.com/506982734.html,
转载于:https://blog.51cto.com/14017122/2299574