Skip to content

Commit 7363a13

Browse files
committed
Improve performance of URI::MailTo::EMAIL_REGEXP
Fix the performance regression at #172 for valid emails. ``` yml prelude: | require 'uri/mailto' n = 1000 re = URI::MailTo::EMAIL_REGEXP benchmark: n.t..t.: re.match?("n.t..t.@docomo.ne.jp") example: re.match?("example@example.info") ``` | |released| 788274b| c5974f0| this| |:--------|-------:|-------:|-------:|-------:| |n.t..t. | 3.795M| 4.864M| 4.993M| 8.739M| | | -| 1.28x| 1.32x| 2.30x| |example | 3.911M| 3.740M| 2.838M| 3.880M| | | 1.38x| 1.32x| -| 1.37x|
1 parent c5974f0 commit 7363a13

File tree

2 files changed

+21
-1
lines changed

2 files changed

+21
-1
lines changed

lib/uri/mailto.rb

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -52,7 +52,11 @@ class MailTo < Generic
5252
HEADER_REGEXP = /\A(?<hfield>(?:%\h\h|[!$'-.0-;@-Z_a-z~])*=(?:%\h\h|[!$'-.0-;@-Z_a-z~])*)(?:&\g<hfield>)*\z/
5353
# practical regexp for email address
5454
# https://html.spec.whatwg.org/multipage/input.html#valid-e-mail-address
55-
EMAIL_REGEXP = /\A(?!\.)(?!.*\.{2})[a-zA-Z0-9.!\#$%&'*+\/=?^_`{|}~-]+(?<!\.)@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*\z/
55+
EMAIL_REGEXP = %r[\A#{
56+
atext = %q[(?:[a-zA-Z0-9!\#$%&'*+\/=?^_`{|}~-]+)]
57+
}(?:\.#{atext})*@#{
58+
label = %q[(?:[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)]
59+
}(?:\.#{label})*\z]
5660
# :startdoc:
5761

5862
#

test/uri/test_mailto.rb

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -210,6 +210,22 @@ def test_check_to
210210
end
211211
end
212212

213+
def test_email_regexp
214+
re = URI::MailTo::EMAIL_REGEXP
215+
216+
rate = 1000
217+
longlabel = '.' + 'invalid'.ljust(63, 'd')
218+
endlabel = ''
219+
pre = ->(n) {'a@invalid' + longlabel*(n*rate) + endlabel}
220+
assert_linear_performance(1..10, pre: pre) do |to|
221+
re =~ to or flunk
222+
end
223+
endlabel = '.' + 'email'.rjust(64, 'd')
224+
assert_linear_performance(1..10, pre: pre) do |to|
225+
re =~ to and flunk
226+
end
227+
end
228+
213229
def test_to_s
214230
u = URI::MailTo.build([nil, 'subject=Ruby'])
215231

0 commit comments

Comments
 (0)
pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy