[英]What is the fastest way to compare beginning of a string?
想象一下這樣的字符串列表: ('{hello world} is awesome', 'Hello world is less awesome', '{hello world} is {awesome} too')
。 我想檢查每個字符串的起始字符周期,我想我有4個選擇:
if re.search(r'^\{', i):
if re.match(r'\{', i):
if i.startswith('{'):
if i[:1] == '{':
哪一個最快? 有沒有比這4個選項更快的選項?
注意:要比較的起始字符串可能更長,而不僅僅是一個字母,例如{hello
最快的是i[0] == value
,因為它直接使用指向基礎數組的指針。 正則表達式需要(至少)解析模式,而startsWith
則需要進行方法調用並在實際比較之前創建該大小的切片。
就像@dsqdfg在評論中說的那樣,python中有一個計時功能,到目前為止我還不知道。 我嘗試測量它們,結果如下:
python -m timeit -s 'text="{hello world}"' 'text[:6] == "{hello"'
1000000 loops, best of 3: 0.224 usec per loop
python -m timeit -s 'text="{hello world}"' 'text.startswith("{hello")'
1000000 loops, best of 3: 0.291 usec per loop
python -m timeit -s 'text="{hello world}"' 'import re' 're.match(r"\{hello", text)'
100000 loops, best of 3: 2.53 usec per loop
python -m timeit -s 'text="{hello world}"' 'import re' 're.search(r"^\{hello", text)'
100000 loops, best of 3: 2.86 usec per loop
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.