Skip to content

Skip regular expressions that cannot match in tokenize() - #229

Open
g4lb wants to merge 1 commit into
scrapy:masterfrom
g4lb:tokenize-first-char
Open

g4lb wants to merge 1 commit into
scrapy:masterfrom
g4lb:tokenize-first-char

Conversation

@g4lb

@g4lb g4lb commented Nov 18, 2026

Copy link
Copy Markdown

For each token, tokenize() runs the whitespace, identifier, hash and number regular expressions until one matches. This change tests the first character before the regular expressions. A DELIM such as >, [ or . (when no digit follows) gets its token at once, and the whitespace regular expression runs only on whitespace. Also, unescape_ident() does not run re.sub() on an identifier without a backslash. The output does not change.

HTMLTranslator().css_to_xpath(), CPython 3.14 Before After Change
10 real selectors 220.4 µs 194.6 µs -11.7%
div with 12 classes 29.4 µs 25.0 µs -14.9%
9 attribute selectors 48.2 µs 36.5 µs -24.3%

On CPython 3.11 and 3.15, the 10 selectors were 10.8% and 12.7% faster. Selectors such as a and div.item use the fast path in parse(), so they do not change.

On CPython 3.11, a token stream with an escape in each identifier was 3.4% slower. Selectors with escapes were 6-9% faster. On CPython, I measured no other slowdown. I used 20 interleaved rounds and a Mann-Whitney test (Apple M5, CPython 3.11, 3.14 and 3.15). On PyPy 3.11, the escape stream was 0-0.8% slower in 4 runs. The other results were in the noise range, or faster. Import time did not change (30 rounds). I did not measure other architectures.

Checks:

  • tox -e py,py311,py315,pypy311,typing,pylint,pre-commit,docs passes.
  • A new test in test_tokenizer shows a . before and after a digit.
  • Old and new outputs matched on 1,000,000 random selectors: tokens, parse trees, specificity, XPath and errors.

@codecov

codecov Bot commented Nov 19, 2026

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 100.00%. Comparing base (51b82b9) to head (a4f8cde).
✅ All tests successful. No failed tests found.

Additional details and impacted files
@@            Coverage Diff            @@
##            master      #229   +/-   ##
=========================================
  Coverage   100.00%   100.00%           
=========================================
  Files            3         3           
  Lines         1034      1043    +9     
  Branches       174       176    +2     
=========================================
+ Hits          1034      1043    +9     

☔ View full report in Codecov by Harness.
📢 Have feedback on the report? Share it here.

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants