Optimize Cursor: skip strrpos on tab-free documents#1119
Open
GromNaN wants to merge 2 commits into
Open
Conversation
benchmark_parse.php measures only the parsing phase (converter initialized once outside the loop) unlike benchmark.php which re-creates the converter on every iteration. Reports min/median/p95/mean over N iterations (default 100 + 10 warmup).
The Cursor constructor previously called strrpos() on every line to find the last tab position, even for documents with no tabs. For tab-free documents (the common case), this was pure overhead — strrpos scans the string backwards and costs 40–165 ns per line depending on length. MarkdownParser now scans the whole document once with str_contains() before the parse loop. When no tabs are found, each Cursor is constructed with $lineCouldHaveTabs=false, setting lastTabPosition=false directly without calling strrpos. Benchmarks (warm, 100 iterations, CommonMarkConverter, sample.md 27 KB): Before: median 4.38 ms After: median 3.92 ms (-10.5%)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Cursor::__construct()calledstrrpos($line, "\t")on every line to locate the last tab position. For tab-free documents this is a full backward scan for no benefit — 40–165 ns/line depending on length.MarkdownParser::parse()now scans the document once withstr_contains()(~3 µs). When no tabs are found,new Cursor($line, false)setslastTabPosition = falsedirectly without callingstrrpos. The$lineCouldHaveTabsparameter defaults totrue, keeping the public API backward compatible.Benchmarks run with
tests/benchmark/benchmark_parse.php(new warm script: converter initialized once, 100 iterations + 10 warmup,hrtime()). PHP 8.5.2, OPcache on, Xdebug off.sample.md(27 KB, 2.9% tabs):Larger corpora from vendor (not committed): CHANGELOG.md 570 KB −5.2%, spec.txt 200 KB −2.8%.