Skip to content

Iteratively parse nested parentheses in PrattParser - #1245

Open
copybara-service[bot] wants to merge 1 commit into
mainfrom
test_984184714
Open

copybara-service[bot] wants to merge 1 commit into
mainfrom
test_984184714

Conversation

@copybara-service

Copy link
Copy Markdown
Contributor

Iteratively parse nested parentheses in PrattParser

Replace the lookahead-based grouping parentheses counter (countGroupingParentheses) with a bottom-up iterative approach in PrattParser.parsePrimary() to eliminate quadratic $O(N^2)$ lookahead scans while keeping $O(1)$ call-stack frames on deeply nested parenthesized expressions.

Benchmarks (CelParserBenchmark, -c opt, parserType=PRATT, parseOnly)

Benchmark Case Before (Mean) After (Mean) Change / Speedup
NESTED_PARENS (N=200) 8,528.69 ns 5,119.12 ns -40.0% (1.67x faster)
NESTED_LEFT_PARENS_CALC (N=200) 951,027.39 ns 27,998.44 ns -97.1% (34.0x faster)
Benchmark Case (Allocations) Before (Bytes / Objs) After (Bytes / Objs) Change
NESTED_PARENS (N=200) 29,200 B / 855 objs 16,336 B / 453 objs -44.1% B / -47.0% objs
NESTED_LEFT_PARENS_CALC (N=200) ~2,690,000 B / ~84,500 objs 127,016 B / 4,577 objs -95.3% B / -94.6% objs

Replace the lookahead-based grouping parentheses counter (`countGroupingParentheses`) with a bottom-up iterative approach in `PrattParser.parsePrimary()` to eliminate quadratic $O(N^2)$ lookahead scans while keeping $O(1)$ call-stack frames on deeply nested parenthesized expressions.

### Benchmarks (`CelParserBenchmark`, `-c opt`, `parserType=PRATT`, `parseOnly`)

| Benchmark Case | Before (Mean) | After (Mean) | Change / Speedup |
| :--- | ---: | ---: | ---: |
| `NESTED_PARENS` (N=200) | 8,528.69 ns | 5,119.12 ns | -40.0% (1.67x faster) |
| `NESTED_LEFT_PARENS_CALC` (N=200) | 951,027.39 ns | 27,998.44 ns | -97.1% (34.0x faster) |

| Benchmark Case (Allocations) | Before (Bytes / Objs) | After (Bytes / Objs) | Change |
| :--- | ---: | ---: | ---: |
| `NESTED_PARENS` (N=200) | 29,200 B / 855 objs | 16,336 B / 453 objs | -44.1% B / -47.0% objs |
| `NESTED_LEFT_PARENS_CALC` (N=200) | ~2,690,000 B / ~84,500 objs | 127,016 B / 4,577 objs | -95.3% B / -94.6% objs |

PiperOrigin-RevId: 984184714
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant