Improve performance of `re.compile()` for patterns with character ranges
未關閉
還沒有人認領這個 Issue。
performance
stdlib
topic-regex
type-feature
- 主要語言
- Python
- 星號
- 77.2k
- 分支
- 36k
- PR 合併指標
- PR 指標待擷取
描述
Feature or enhancement
Proposal:
re._compiler._optimize_charset builds a 256-byte (or wider) charmap for character classes. On main it is filled with a loop:
for i in range(av[0], av[1] + 1):
charmap[i] = 1
Replacing the loop with a single bytearray slice is faster.
Benchmark results on pyperformance regex_compile
main (86.2 ± 1.4 ms) -> PR (78.5 ± 1.6 ms): 1.10x faster
Microbenchmarks:
compile-charsets-small: 2.80 ± 0.04 ms -> 1.22 ± 0.02 ms: 2.29x faster
compile-charsets-big: 1.46 ± 0.03 ms -> 1.36 ± 0.03 ms: 1.08x faster
Geometric mean: 1.57x faster
The "small" case oversamples wide ranges ([\x00-\xff], BMP range) which benefit most. The "big" case has mostly small ASCII ranges where the slice-fill construction (b'\x01' * n) competes with the loop savings.
microbench script
"""Microbench for the bytearray slice-fill optimization in
re._compiler._optimize_charset (RANGE handler)."""
import pyperf
import re
SMALL_PATTERNS = [
r'[a-zA-Z0-9_]+',
r'[^\s\d]+',
r'[a-z][A-Z][0-9]',
r'[\x00-\xff]', # full byte range
r'[Ā-]+', # BMP range, hits growth path
r'[a-zA-Z0-9!@#$%^&*()_+\-=\[\]{};:\'",.<>/?\\|`~]+',
r'[0-9a-fA-F]{2,8}',
r'[ -~]+', # all printable ASCII
]
BIG_PATTERN = (
r'^([a-zA-Z][a-zA-Z0-9_\-]*)\s*'
r'([\x20-\x7e]*)\s*'
r'([-ÿĀ-ɏ]+)?\s*'
r'([0-9]{1,4}[\-/.][0-9]{1,2}[\-/.][0-9]{1,4})?\s*'
r'([^\s,;:]+)$'
)
def compile_small():
for _ in range(8):
for p in SMALL_PATTERNS:
re.purge()
re.compile(p)
def compile_big():
for _ in range(10):
re.purge()
re.compile(BIG_PATTERN)
runner = pyperf.Runner()
runner.bench_func('compile-charsets-small', compile_small)
runner.bench_func('compile-charsets-big', compile_big)
Has this already been discussed elsewhere?
No response given
Links to previous discussion of this feature:
No response
Linked PRs
- gh-149428
貢獻指南
從這裡開始
- 先讀完整個 Issue,再讀專案的貢獻指南。
- 在 Issue 下留言說明你要接手 —— 這能避免兩個人做同樣的事。
- Fork 儲存庫,在一個分支上完成修改。
- 送出 Pull Request,並在描述裡引用這個 Issue 編號。
研究方向
從 re._compiler._optimize_charset 開始,著重檢視填入 charmap 的 RANGE 處理器。檢閱相關的 PR gh-149428,並比較其對小字元範圍和寬字元範圍的行為。完成的標準是範圍處理仍然正確,且 regex_compile 和提供的微基準測試能夠重現預期的效能改善。
由索引模型根據 Issue 內容生成。
評估
- 技術堆疊
- python
- 領域
- performance
- Issue 類型
- 功能
- 難度
- 2/5
- 預估耗時
- 1-3 小時
- 活躍度
- 停滯
- 描述清晰度
- 描述清楚
- 新手友好度
- 25/100