Skip to content

Commit b4daab2

Browse files
committed
Optimise searching for placeholders
If a string doesn’t have an opening parentheses then we can guarantee it doesn’t have any placeholders in it. We can take advantage of this to skip the expensive regex search. Benchmark for string with no placeholders: ```shell python -m timeit -s "import random; import string; from notifications_utils.field import Field; s = ''.join(random.choices(string.ascii_uppercase + string.digits + string.whitespace, k=1000))" "Field(s).placeholders" ``` Before > 50000 loops, best of 5: 7.68 usec per loop After > 500000 loops, best of 5: 536 nsec per loop 14× faster Benchmark for same string with one placeholder right at the end: ```shell python -m timeit -s "import random; import string; from notifications_utils.field import Field; s = ''.join(random.choices(string.ascii_uppercase + string.digits + string.whitespace, k=1000)) + '((name))'" "Field(s).placeholders" ``` Before > 50000 loops, best of 5: 9.06 usec per loop After > 50000 loops, best of 5: 9.06 usec per loop No change.
1 parent 5811563 commit b4daab2

1 file changed

Lines changed: 1 addition & 1 deletion

File tree

notifications_utils/field.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -161,7 +161,7 @@ def formatted(self):
161161

162162
@property
163163
def placeholders(self):
164-
if not getattr(self, "content", ""):
164+
if not self.content or "(" not in self.content:
165165
return InsensitiveSet()
166166
return InsensitiveSet(Placeholder(body).name for body in re.findall(self.placeholder_pattern, self.content))
167167

0 commit comments

Comments
 (0)