Skip to content

Commit 119f1c2

Browse files
committed
Enumerate over text when finding unquoted char
Enumerating rather than using a while loop saves significant CPU when looking for an unquoted character. This ends up improving the benchmark ~20% on its own. Signed-off-by: Chris Marchbanks <[email protected]>
1 parent fb5f6d7 commit 119f1c2

File tree

1 file changed

+7
-8
lines changed

1 file changed

+7
-8
lines changed

prometheus_client/parser.py

Lines changed: 7 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -139,27 +139,26 @@ def _next_term(text: str, openmetrics: bool) -> Tuple[str, str]:
139139
return term.strip(), sublabels.strip()
140140

141141

142-
def _next_unquoted_char(text: str, chs: str, startidx: int = 0) -> int:
142+
def _next_unquoted_char(text: str, chs: Optional[str], startidx: int = 0) -> int:
143143
"""Return position of next unquoted character in tuple, or -1 if not found.
144144
145145
It is always assumed that the first character being checked is not already
146146
inside quotes.
147147
"""
148-
i = startidx
149148
in_quotes = False
150149
if chs is None:
151150
chs = string.whitespace
152-
while i < len(text):
153-
if text[i] == '"' and not _is_character_escaped(text, i):
151+
152+
for i, c in enumerate(text[startidx:]):
153+
if c == '"' and not _is_character_escaped(text, startidx + i):
154154
in_quotes = not in_quotes
155155
if not in_quotes:
156-
if text[i] in chs:
157-
return i
158-
i += 1
156+
if c in chs:
157+
return startidx + i
159158
return -1
160159

161160

162-
def _last_unquoted_char(text: str, chs: str) -> int:
161+
def _last_unquoted_char(text: str, chs: Optional[str]) -> int:
163162
"""Return position of last unquoted character in list, or -1 if not found."""
164163
i = len(text) - 1
165164
in_quotes = False

0 commit comments

Comments
 (0)