Optimize grammars by avoiding repeated expressions
masterTo improve performance and reduce memory usage, avoid defining the same expression multiple times in your grammar. Instead, define the expression as its own rule and reference that rule wherever it is needed.
Why this matters:
- Caching: Parsimoniuos uses expression object identity for fast cache lookups. Referencing a single rule ensures better cache hits.
- RAM Efficiency: Repeating expressions can lead to increased RAM usage, as the parser may cache an integer for every character in the text for every unique expression object.
Balancing Regex vs. Rules:
- Large Regexes: Jamming more logic into a single regex executes faster because it avoids running Python code between segments.
- Broken-up Rules: Breaking expressions into smaller, reusable rules provides better cache performance if those pieces are used in multiple places.