Skip to content

Iteratively parse nested parentheses in PrattParserWorker - #2278

Open
copybara-service[bot] wants to merge 1 commit into
masterfrom
test_984557444
Open

copybara-service[bot] wants to merge 1 commit into
masterfrom
test_984557444

Conversation

@copybara-service

Copy link
Copy Markdown

Iteratively parse nested parentheses in PrattParserWorker

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

Benchmarks (pratt_parser_benchmark, -c opt --dynamic_mode=off)

Benchmark Case Before (Mean) After (Mean) Change / Speedup
BM_Pratt_ParseNestedParentheses/10 724 ns 535 ns -26.1% (1.35x faster)
BM_Pratt_ParseNestedParentheses/50 2,484 ns 1,625 ns -34.6% (1.53x faster)
BM_Pratt_ParseNestedParentheses/200 8,859 ns 5,427 ns -38.7% (1.63x faster)
BM_Pratt_ParseNestedLeftParenthesesCalc/10 7,876 ns 3,397 ns -56.9% (2.32x faster)
BM_Pratt_ParseNestedLeftParenthesesCalc/50 112,539 ns 14,518 ns -87.1% (7.75x faster)
BM_Pratt_ParseNestedLeftParenthesesCalc/200 1,583,442 ns 57,375 ns -96.4% (27.6x faster)

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

### Benchmarks (`pratt_parser_benchmark`, `-c opt --dynamic_mode=off`)

| Benchmark Case | Before (Mean) | After (Mean) | Change / Speedup |
| :--- | ---: | ---: | ---: |
| `BM_Pratt_ParseNestedParentheses/10` | 724 ns | 535 ns | -26.1% (1.35x faster) |
| `BM_Pratt_ParseNestedParentheses/50` | 2,484 ns | 1,625 ns | -34.6% (1.53x faster) |
| `BM_Pratt_ParseNestedParentheses/200` | 8,859 ns | 5,427 ns | -38.7% (1.63x faster) |
| `BM_Pratt_ParseNestedLeftParenthesesCalc/10` | 7,876 ns | 3,397 ns | -56.9% (2.32x faster) |
| `BM_Pratt_ParseNestedLeftParenthesesCalc/50` | 112,539 ns | 14,518 ns | -87.1% (7.75x faster) |
| `BM_Pratt_ParseNestedLeftParenthesesCalc/200` | 1,583,442 ns | 57,375 ns | -96.4% (27.6x faster) |

PiperOrigin-RevId: 984557444
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