Добавлять ^ https?: // быстрее, потому что регулярное выражение не нужно искать везде в строке, только в начале:
domains = ['domain1.com', 'domain2.com', 'domain3.com'] * 1000
env = {'HTTP_REFERER' => 'http://domain4.com/'}
re = Regexp.new('^https?:\/\/(' + domains.join('|') + ')')
500000.times do
env['HTTP_REFERER'] =~ re
end
Редактировать
Ну, есть и тесты, и тесты @Jonas Elfstrom, чтобы принять пирог :) Давайте попробуем показать, почему вы не должны относиться ко всем тестам серьезно:
domains=[]
3000.times {|i| domains<<"domain#{i}.com"}
# let's assume the referrer is in the top 10 of whitelisted referrers.
# I'm not trying to introduce bias, I actually think that's reasonable.
env = {'HTTP_REFERER' => 'http://domain10.com/'}
Benchmark.bm do |benchmark|
puts "pguardiario regex"
benchmark.report do
re = Regexp.new('^https?:\/\/(' + domains.join('|') + ')')
100000.times do
env['HTTP_REFERER'] =~ re
end
end
puts "Only the set look-up"
benchmark.report do
DOMAINS = domains.to_set
domain_tld = "domain4711.com" # huh?
# Um, excuse me? You think you can get away with hardcoding that? lol :)
100000.times do
# how about if we parse on the fly like we would have to do in real life.
domain_tld = URI.parse(env['HTTP_REFERER']).host
DOMAINS.include? domain_tld
end
end
end
user system total real
регулярное выражение pguardiario
0,203000 0,000000 0,203000 (0,200012)
Только установленный просмотр
2.371000 0.000000 2.371000 (2.386136)
Результат: Извини @Jonas, даже не близко.