Skip to content

Commit

Permalink
Minor profiling-driven performance improvement for regex parser
Browse files Browse the repository at this point in the history
  • Loading branch information
noamgat committed Dec 21, 2023
1 parent 11d4beb commit 39ad002
Showing 1 changed file with 6 additions and 6 deletions.
12 changes: 6 additions & 6 deletions lmformatenforcer/regexparser.py
Original file line number Diff line number Diff line change
Expand Up @@ -42,13 +42,13 @@ def add_character(self, new_character: str) -> 'RegexParser':
symbol = anything_else
transition = fsm.alphabet[symbol]

# Missing transition = transition to dead state
if not (state in fsm.map and transition in fsm.map[state]):
try:
# Prefer try-catch to checking if transition exists to avoid double lookup perf hit in valid case
state = fsm.map[state][transition] # type: ignore
return RegexParser(self.context, self.config, state)
except KeyError:
# Missing transition = transition to dead state
return RegexParser(self.context, self.config, RegexParser.INVALID_STATE)

state = fsm.map[state][transition]

return RegexParser(self.context, self.config, state)

def can_end(self) -> bool:
return self.current_state in self.context.pattern.finals
Expand Down

0 comments on commit 39ad002

Please sign in to comment.