diff --git a/.github/workflows/benchmark.php b/.github/workflows/benchmark.php
new file mode 100644
index 0000000..8f07c56
--- /dev/null
+++ b/.github/workflows/benchmark.php
@@ -0,0 +1,82 @@
+xpath('//variant') as $variant) {
+ $class = (string)$variant->xpath('ancestor::benchmark')[0]['class'];
+ $name = substr($class, strrpos($class, '\\') + 1);
+ $results[$name][(string)$variant->{'parameter-set'}['name']] = (float)$variant->stats['mode'];
+ }
+
+ return $results;
+}
+
+function duration(float $microseconds): string
+{
+ return match(true) {
+ $microseconds < 1000 => sprintf('%.1f µs', $microseconds),
+ $microseconds < 1000000 => sprintf('%.1f ms', $microseconds / 1000),
+ default => sprintf('%.2f s', $microseconds / 1000000),
+ };
+}
+
+function commit(string $ref, string $sha): string
+{
+ return ''.$ref.' ('.substr($sha, 0, 7).')';
+}
+
+[, $baseFile, $headFile, $tableFile] = $argv;
+$base = results($baseFile);
+$head = results($headFile);
+
+$counts = array();
+$changes = array();
+$ratios = array();
+foreach($head as $benchmark => $cases) {
+ $counts[$benchmark] = array('improved' => 0, 'regressed' => 0, 'untouched' => 0, 'new' => 0);
+ foreach($cases as $case => $time) {
+ if(false === isset($base[$benchmark][$case])) {
+ $counts[$benchmark]['new']++;
+ continue;
+ }
+ $efficiency = $base[$benchmark][$case] / $time - 1;
+ if(abs($efficiency) < THRESHOLD) {
+ $counts[$benchmark]['untouched']++;
+ continue;
+ }
+ $counts[$benchmark][$efficiency > 0 ? 'improved' : 'regressed']++;
+ $changes[] = array($efficiency > 0 ? '⚡' : '❌', $benchmark.': '.$case, $base[$benchmark][$case], $time, $efficiency);
+ $ratios[] = 1 + $efficiency;
+ }
+}
+usort($changes, fn(array $a, array $b) => abs($b[4]) <=> abs($a[4]));
+
+$impact = $ratios ? array_product($ratios) ** (1 / count($ratios)) - 1 : 0.0;
+echo "\n";
+echo match(true) {
+ !$ratios => '## Merging this PR will **not alter performance**',
+ $impact >= 0 => sprintf('## Merging this PR will **improve performance by %.2f%%**', 100 * $impact),
+ default => sprintf('## Merging this PR will **degrade performance by %.2f%%**', -100 * $impact),
+}, "\n\n";
+
+echo "| Benchmark | ⚡ improved | ❌ regressed | ✅ untouched | 🆕 new |\n";
+echo "| --------- | ---------- | ----------- | ----------- | ------ |\n";
+foreach($counts as $benchmark => $count) {
+ printf("| `%s` | %d | %d | %d | %d |\n", $benchmark, $count['improved'], $count['regressed'], $count['untouched'], $count['new']);
+}
+
+if($changes) {
+ echo "\n### Performance Changes\n\n";
+ echo "| | Benchmark | `BASE` | `HEAD` | Efficiency |\n";
+ echo "| --- | --------- | ------ | ------ | ---------- |\n";
+ foreach($changes as [$icon, $name, $before, $after, $efficiency]) {
+ printf("| %s | `%s` | %s | %s | %+.2f%% |\n", $icon, $name, duration($before), duration($after), 100 * $efficiency);
+ }
+}
+
+printf("\nA benchmark is changed when its efficiency (`BASE` / `HEAD` - 1) is at least %d%% in either direction.\n", 100 * THRESHOLD);
+echo "\nAll benchmarks
\n\n```\n", rtrim(file_get_contents($tableFile)), "\n```\n\n \n";
+echo "\n---\n\nComparing ", commit(getenv('HEAD_REF'), getenv('HEAD_SHA')), ' with ', commit(getenv('BASE_REF'), getenv('BASE_SHA')), "\n";
diff --git a/.github/workflows/test.yaml b/.github/workflows/test.yaml
index a1de24c..112e37b 100644
--- a/.github/workflows/test.yaml
+++ b/.github/workflows/test.yaml
@@ -68,3 +68,46 @@ jobs:
php vendor/bin/infection --static-analysis-tool=mago $DIFF
env:
BASE_REF: '${{ github.base_ref }}'
+
+ benchmark:
+ if: "github.event_name == 'pull_request'"
+ runs-on: 'ubuntu-latest'
+ permissions:
+ contents: 'read'
+ pull-requests: 'write'
+ steps:
+ - name: 'Checkout'
+ uses: 'actions/checkout@v4'
+ with:
+ fetch-depth: 0
+ - name: 'Install PHP'
+ uses: 'shivammathur/setup-php@v2'
+ with:
+ php-version: '8.5'
+ tools: 'composer:v2'
+ coverage: 'none'
+ - name: 'PHPBench'
+ shell: 'bash'
+ run: |
+ composer require --dev -W phpbench/phpbench
+ rm -rf src && git checkout "origin/$BASE_REF" -- src
+ php vendor/bin/phpbench run --tag=base --progress=none --dump-file=benchmark-base.xml
+ rm -rf src && git checkout HEAD -- src
+ php vendor/bin/phpbench run --ref=base --report=aggregate --progress=none --no-ansi --dump-file=benchmark-head.xml | tee benchmark.txt
+ BASE_SHA=$(git rev-parse "origin/$BASE_REF") php .github/workflows/benchmark.php benchmark-base.xml benchmark-head.xml benchmark.txt > benchmark.md
+ env:
+ BASE_REF: '${{ github.base_ref }}'
+ HEAD_REF: '${{ github.head_ref }}'
+ HEAD_SHA: '${{ github.event.pull_request.head.sha }}'
+ - name: 'Benchmark comment'
+ if: "github.event.pull_request.head.repo.full_name == github.repository"
+ run: |
+ ID=$(gh api "repos/$GITHUB_REPOSITORY/issues/$PR/comments" --paginate --jq '.[] | select(.user.login == "github-actions[bot]" and (.body | startswith(""))) | .id' | tail -n 1)
+ if [ -n "$ID" ]; then
+ gh api -X PATCH "repos/$GITHUB_REPOSITORY/issues/comments/$ID" -F body=@benchmark.md > /dev/null
+ else
+ gh pr comment "$PR" --repo "$GITHUB_REPOSITORY" --body-file benchmark.md
+ fi
+ env:
+ GH_TOKEN: '${{ github.token }}'
+ PR: '${{ github.event.pull_request.number }}'
diff --git a/.gitignore b/.gitignore
index 242a541..8de02f3 100644
--- a/.gitignore
+++ b/.gitignore
@@ -5,3 +5,4 @@ vendor
composer.lock
coverage
coverage.xml
+.phpbench
diff --git a/phpbench.json b/phpbench.json
new file mode 100644
index 0000000..82ecacd
--- /dev/null
+++ b/phpbench.json
@@ -0,0 +1,9 @@
+{
+ "$schema": "./vendor/phpbench/phpbench/phpbench.schema.json",
+ "runner.bootstrap": "vendor/autoload.php",
+ "runner.path": "tests/Benchmark",
+ "runner.file_pattern": "*Bench.php",
+ "runner.php_config": {
+ "memory_limit": "1G"
+ }
+}
diff --git a/tests/Benchmark/ParserBench.php b/tests/Benchmark/ParserBench.php
new file mode 100644
index 0000000..060410b
--- /dev/null
+++ b/tests/Benchmark/ParserBench.php
@@ -0,0 +1,60 @@
+parser = match($params['parser']) {
+ 'regular' => new RegularParser(),
+ 'regex' => new RegexParser(),
+ 'hybrid' => new HybridParser(),
+ 'wordpress' => new WordpressParser(),
+ };
+ $this->text = Texts::get($params['text'], $params['times']);
+ $this->loops = $params['loops'];
+ }
+
+ #[ParamProviders('provideCases')]
+ public function benchParse(): void
+ {
+ for($i = 0; $i < $this->loops; $i++) {
+ $this->parser->parse($this->text);
+ }
+ }
+
+ public function provideCases(): \Generator
+ {
+ $times = array('article' => 8, 'dense' => 60, 'nested' => 50, 'deep' => 10, 'brackets' => 200);
+ $loops = array(
+ 'regular' => array('article' => 100, 'dense' => 50, 'nested' => 50, 'deep' => 5, 'brackets' => 10),
+ 'regex' => array('article' => 2000, 'dense' => 200, 'nested' => 1000, 'deep' => 2000, 'brackets' => 10),
+ 'hybrid' => array('article' => 2000, 'dense' => 200, 'nested' => 500, 'deep' => 200, 'brackets' => 200),
+ 'wordpress' => array('article' => 2000, 'dense' => 500, 'nested' => 2000, 'deep' => 5000, 'brackets' => 20),
+ );
+ foreach($loops as $parser => $texts) {
+ foreach($texts as $text => $count) {
+ yield $parser.' '.$text => array('parser' => $parser, 'text' => $text, 'times' => $times[$text], 'loops' => $count);
+ }
+ }
+ }
+}
diff --git a/tests/Benchmark/ProcessorBench.php b/tests/Benchmark/ProcessorBench.php
new file mode 100644
index 0000000..d3020f5
--- /dev/null
+++ b/tests/Benchmark/ProcessorBench.php
@@ -0,0 +1,71 @@
+setDefault(function(ShortcodeInterface $s) {
+ return '<'.$s->getName().'>'.$s->getContent().''.$s->getName().'>';
+ });
+ $handlers->add('url', function(ShortcodeInterface $s) {
+ return ''.$s->getContent().'';
+ });
+ $handlers->add('button', function(ShortcodeInterface $s) {
+ return ''.$s->getContent().'';
+ });
+ $handlers->add('img', function(ShortcodeInterface $s) {
+ return '
';
+ });
+ $handlers->add('icon', function(ShortcodeInterface $s) {
+ return '';
+ });
+
+ $parser = 'hybrid' === $params['parser'] ? new HybridParser() : new RegularParser();
+ $this->processor = new Processor($parser, $handlers);
+ $this->text = Texts::get($params['text'], $params['times']);
+ $this->loops = $params['loops'];
+ }
+
+ #[ParamProviders('provideCases')]
+ public function benchProcess(): void
+ {
+ for($i = 0; $i < $this->loops; $i++) {
+ $this->processor->process($this->text);
+ }
+ }
+
+ public function provideCases(): \Generator
+ {
+ $times = array('article' => 8, 'dense' => 250, 'nested' => 50, 'deep' => 1);
+ $loops = array(
+ 'regular' => array('article' => 50, 'dense' => 2, 'nested' => 10, 'deep' => 2),
+ 'hybrid' => array('article' => 200, 'dense' => 2, 'nested' => 50, 'deep' => 20),
+ );
+ foreach($loops as $parser => $texts) {
+ foreach($texts as $text => $count) {
+ yield $parser.' '.$text => array('parser' => $parser, 'text' => $text, 'times' => $times[$text], 'loops' => $count);
+ }
+ }
+ }
+}
diff --git a/tests/Benchmark/Texts.php b/tests/Benchmark/Texts.php
new file mode 100644
index 0000000..3535b22
--- /dev/null
+++ b/tests/Benchmark/Texts.php
@@ -0,0 +1,34 @@
+ self::PROSE.' This is [b]important[/b], so [url href="https://example.com/articles/42"]read more[/url].'."\n\n"
+ .self::PROSE_UTF8."\n\n"
+ .'[img src="/media/photo-42.jpg" alt="Zdjęcie 📷" /]'."\n\n"
+ .'[quote author="Grzegorz Brzęczyszczykiewicz"]'.self::PROSE.'[/quote]'."\n\n",
+ 'dense' => '[button url="https://example.com/buy?id=42" color=blue size=large]Buy now[/button] [icon=star /] [tag]php[/tag] [img src=photo.jpg alt="A photo" width=640 /]'."\n",
+ 'nested' => '[row][col width=6][card title="First card"][b]Bold[/b] and [i]italic[/i] text.[/card][/col][col width=6][card title="Second card"][url href="https://example.com"]A link[/url][/card][/col][/row]'."\n",
+ 'deep' => self::deep(100),
+ 'brackets' => 'As shown in the survey[1], most results [citation needed] were confirmed later[2]; see [the documentation](https://example.com/docs) for details. ',
+ }, $times);
+ }
+
+ private static function deep(int $depth): string
+ {
+ $open = '';
+ $close = '';
+ for($i = 1; $i <= $depth; $i++) {
+ $open .= '[d'.$i.']';
+ $close = '[/d'.$i.']'.$close;
+ }
+
+ return $open.'x'.$close."\n";
+ }
+}