Skip to content

Reuse the header lookup pattern across response headers - #13220

Merged
Seldaek merged 2 commits into
composer:mainfrom
andreybolonin:perf/http-header-pattern-reuse
Nov 3, 2026
Merged

Seldaek merged 2 commits into
composer:mainfrom
andreybolonin:perf/http-header-pattern-reuse

Conversation

@andreybolonin

Copy link
Copy Markdown
Contributor

Response::findHeaderValue() rebuilds and quotes the same regex for every response header. Construct the pattern once before iterating, with an early return for an empty header array to avoid allocating an unused pattern.

Keep the existing regex and scan order, preserving case-insensitive names, whitespace handling and the last matching header value across redirects. Add regression coverage for duplicate headers, empty and whitespace-only values, mixed case, regex metacharacters and nonsequential array keys.

Measurements

Baseline: e1460b9e8. PHP 8.5.12 CLI/macOS, CLI OPcache and JIT disabled. Median of seven warmed rounds with alternating baseline/candidate order. Memory is the approximate maximum incremental PHP peak allocation over initialized loop state, measured before recording results; it is not process RSS. A zero figure means no additional tracked allocations, not zero total memory.

Scenario Calls/round Before ms After ms Time reduction Before peak bytes After peak bytes
findHeaderValue 0 headers missing 10000 0.365 0.367 -0.5% 0 0
findHeaderValue 0 headers last 10000 0.365 0.367 -0.5% 0 0
findHeaderValue 0 headers repeated 10000 0.375 0.376 -0.1% 0 0
findHeaderValue 1 headers missing 10000 3.002 3.049 -1.6% 152 152
findHeaderValue 1 headers last 10000 3.658 3.752 -2.6% 424 424
findHeaderValue 1 headers repeated 10000 3.477 3.537 -1.7% 416 416
findHeaderValue 10 headers missing 10000 25.926 18.917 27.0% 208 208
findHeaderValue 10 headers last 10000 27.887 19.681 29.4% 424 424
findHeaderValue 10 headers repeated 10000 30.035 22.646 24.6% 472 472
findHeaderValue 30 headers missing 10000 77.140 53.733 30.3% 208 208
findHeaderValue 30 headers last 10000 78.117 54.596 30.1% 424 424
findHeaderValue 30 headers repeated 10000 87.424 63.631 27.2% 472 472
findHeaderValue 100 headers missing 10000 257.135 176.998 31.2% 208 208
findHeaderValue 100 headers last 10000 258.218 178.218 31.0% 424 424
findHeaderValue 100 headers repeated 10000 289.031 209.211 27.6% 472 472

The fixtures cover missing, last and repeated matching headers, including multiple matches to check last-value semantics. Improvements are around 24–31% for 10–100 headers but smaller for a single header. Empty input allocates no additional memory. No universal >=20% or complete Composer-command improvement is claimed.

Validation

  • 40 tests, 87 assertions, no failures/errors.
  • Exploratory differential checks: 10,000 generated header batches including duplicates, mixed case, whitespace, regex metacharacters, control characters, and sparse/string keys.
  • Targeted PHPStan analysis of the modified source and tests passed with the repository configuration plus a local PHP 7.4 target override (installed PHPStan 1.x cannot target the host PHP 8.5 version).
  • git diff --check passed.
php vendor/bin/simple-phpunit --filter '/Composer\\Test\\Util\\(Http\\(ResponseTest|CurlDownloaderTest)|HttpDownloaderTest)::/'
Reproduce the measurements

Save this script outside the repository and run php /path/to/benchmark.php from this PR checkout root. It reads the baseline with git show and loads baseline/candidate under distinct class names without changing source files. The benchmark requires PHP 8.2+ for memory_reset_peak_usage(); this requirement does not apply to the implementation changes.

<?php
// Run from the PR checkout root, on PHP 8.2+ for memory_reset_peak_usage().
require getcwd().'/vendor/autoload.php';
$source = shell_exec('git show e1460b9e8:src/Composer/Util/Http/Response.php');
if (!is_string($source)) { throw new RuntimeException('Could not read baseline'); }
eval(substr(str_replace('class Response', 'class ResponseBaseline', $source), 5));
$source = file_get_contents(getcwd().'/src/Composer/Util/Http/Response.php');
eval(substr(str_replace('class Response', 'class ResponseCandidate', $source), 5));
function bench(string $label, callable $a, callable $b, int $calls): void {
 $times=[[],[]];$peaks=[0,0];$a();$b();
 for($r=0;$r<7;$r++) foreach($r%2?[1,0]:[0,1] as $v){
  $fn=$v?$b:$a;gc_collect_cycles();memory_reset_peak_usage();$m=memory_get_usage();$t=hrtime(true);
  for($i=0;$i<$calls;$i++){$fn();}
  $elapsed=(hrtime(true)-$t)/1e6;$peak=memory_get_peak_usage()-$m;
  $times[$v][]=$elapsed;$peaks[$v]=max($peaks[$v],$peak);
 }
 sort($times[0]);sort($times[1]);printf("%s | %d calls | %.3f -> %.3f ms | %.1f%% less time | %d -> %d peak bytes\n",$label,$calls,$times[0][3],$times[1][3],100*(1-$times[1][3]/$times[0][3]),...$peaks);
}
use Composer\Util\Http\ResponseBaseline as A;
use Composer\Util\Http\ResponseCandidate as B;
foreach([0,1,10,30,100] as $n){
 $headers=[];for($i=0;$i<$n;$i++)$headers[]='X-Test-'.$i.': value';
 foreach(['missing','last','repeated'] as $type){
  if($n&&$type==='last')$headers[$n-1]='Content-Type: application/json';
  if($type==='repeated')for($i=0;$i<$n;$i+=2)$headers[$i]='content-type: text/plain';
  if(A::findHeaderValue($headers,'Content-Type')!==B::findHeaderValue($headers,'Content-Type'))throw new Exception('mismatch');
  bench('findHeaderValue '.$n.' headers '.$type,static function()use($headers){return A::findHeaderValue($headers,'Content-Type');},static function()use($headers){return B::findHeaderValue($headers,'Content-Type');},10000);
 }
}

@Seldaek

Seldaek commented Nov 3, 2026

Copy link
Copy Markdown
Member

This highlighted a weird behavior with Header: returning " " so I fixed that 👍🏻 The perf gains are probably not huge tho here.

@Seldaek
Seldaek merged commit f6840e6 into composer:main Nov 3, 2026
23 checks passed
gemmaro pushed a commit to phpusers-ja/composer that referenced this pull request Nov 9, 2026
mwalbeck pushed a commit to mwalbeck/docker-composer that referenced this pull request Nov 22, 2026
This PR contains the following updates:

| Package | Update | Change |
|---|---|---|
| [composer/composer](https://github.com/composer/composer) | minor | `2.10.3` → `2.11.2` |

---

### Release Notes

<details>
<summary>composer/composer (composer/composer)</summary>

### [`v2.11.2`](https://github.com/composer/composer/blob/HEAD/CHANGELOG.md#2112-2026-11-11)

[Compare Source](composer/composer@2.11.1...2.11.2)

- Security: Fixed arbitrary command execution via the `prevent_url_access_callable` transport option being loaded from `composer.lock` / `vendor/composer/installed.json` (GHSA-jhfp-4ppm-crmm)
  - Security: Fixed malicious zip archives being able to write files outside of the package directory via symlinked entries when extraction falls back from `unzip` to `ZipArchive` (GHSA-w6hj-6587-3jh5)
  - Security: Fixed inline repository HTTP credentials being sent to dist mirrors on other hosts supplied by a crafted `composer.lock` / `vendor/composer/installed.json` (GHSA-x82q-x274-r6pq)
  - Security: Updated the bundled symfony/filesystem to a version fixing a disclosed vulnerability present in the one shipped with 2.11.1 (GHSA-6prc-h956-hxjq)
  - Security: Fixed `Authorization` and `Cookie` headers set in request options, e.g. via a repository's `http.header` option, being resent when following a redirect to another origin ([#&#8203;13253](composer/composer#13253))
  - Security: Fixed non-auth config settings being read from a project's `auth.json` and the `COMPOSER_AUTH` env var, and `home` being read from a project's composer.json, these are now ignored with a warning ([#&#8203;13208](composer/composer#13208))
  - Security: Fixed IPs blocked by the `prevent_ip_access_callable` transport option only being rejected after the request had been sent, and rejected in-flight downloads not being stopped ([#&#8203;13255](composer/composer#13255))
  - Added `exclude-branches` option to VCS repositories to skip branches matching the given patterns, e.g. bot-managed ones ([#&#8203;13235](composer/composer#13235))
  - Added support for setting `allow-git-fallback` to `false` in GitLab, Bitbucket and Forgejo repositories to fail on API errors instead of falling back to a git clone ([#&#8203;13234](composer/composer#13234))
  - Added a 30 seconds stall timeout so downloads from a server which accepts the connection but never responds are aborted and retried instead of hanging for 300 seconds, configurable or disabled via the `COMPOSER_HTTP_STALL_TIMEOUT` env var ([#&#8203;13243](composer/composer#13243))
  - Improved performance of security advisory lookups by querying the API only once per package name ([#&#8203;13202](composer/composer#13202))
  - Improved performance of VCS repository updates by skipping the default branch lookup when the git mirror is up to date ([#&#8203;13224](composer/composer#13224))
  - Improved performance and memory usage of dependency resolution, package loading and sorting, and repository traversal ([#&#8203;13187](composer/composer#13187), [#&#8203;13188](composer/composer#13188), [#&#8203;13194](composer/composer#13194), [#&#8203;13197](composer/composer#13197), [#&#8203;13200](composer/composer#13200), [#&#8203;13211](composer/composer#13211), [#&#8203;13217](composer/composer#13217), [#&#8203;13218](composer/composer#13218))
  - Improved performance with micro-optimizations in path and URL handling, lock file and `installed.php` generation, archiving and TLS/HTTP helpers ([#&#8203;13189](composer/composer#13189), [#&#8203;13190](composer/composer#13190), [#&#8203;13191](composer/composer#13191), [#&#8203;13192](composer/composer#13192), [#&#8203;13193](composer/composer#13193), [#&#8203;13195](composer/composer#13195), [#&#8203;13196](composer/composer#13196), [#&#8203;13198](composer/composer#13198), [#&#8203;13214](composer/composer#13214), [#&#8203;13215](composer/composer#13215), [#&#8203;13216](composer/composer#13216), [#&#8203;13220](composer/composer#13220), [#&#8203;13222](composer/composer#13222))
  - Fixed `config` failing with a schema error or corrupting composer.json by turning nested `{}` into `[]` when adding or removing dotted sub-keys ([#&#8203;13210](composer/composer#13210))
  - Fixed `config --unset`, `remove` and `require` leaving in place or duplicating composer.json keys which are set to `null` ([#&#8203;13225](composer/composer#13225))
  - Fixed dist URLs of codeberg.org packages and bitbucket zip archives not being updated when requiring a specific commit with `dev-branch#hash` ([#&#8203;13242](composer/composer#13242))
  - Fixed an undefined array key warning hiding the real error when curl 8.23+ fails to parse a URL ([#&#8203;13252](composer/composer#13252))

### [`v2.11.1`](https://github.com/composer/composer/blob/HEAD/CHANGELOG.md#2111-2026-10-30)

[Compare Source](composer/composer@2.11.0...2.11.1)

- Added a warning when the cache dir is on a Windows drive while running in WSL, as this makes filesystem operations very slow ([#&#8203;13175](composer/composer#13175))
  - Fixed GitLab CI job tokens failing to authenticate against the GitLab Composer package registry, which requires HTTP Basic auth rather than the `JOB-TOKEN` header ([#&#8203;13180](composer/composer#13180))
  - Fixed every update aborting with a `SecurityException` when a PHP extension reports a name that is not a valid platform package name ([#&#8203;13184](composer/composer#13184))
  - Fixed `require` and `remove` dropping empty `require`/`require-dev`/`repositories` keys from composer.json when the command had not emptied them itself ([#&#8203;13178](composer/composer#13178))
  - Fixed a PHP 8.6 deprecation warning from composer/ca-bundle ([`8bf8c27`](composer/composer@8bf8c27))
  - Fixed invalid `custom-headers` auth entries being sent as-is, they are now ignored with a warning ([#&#8203;13181](composer/composer#13181))

### [`v2.11.0`](https://github.com/composer/composer/blob/HEAD/CHANGELOG.md#2110-2026-10-29)

[Compare Source](composer/composer@2.10.3...2.11.0)

- Security: Fixed package names in `vendor/composer/installed.json` being able to escape the vendor directory during install and reinstall (GHSA-c968-33g3-wh7p)
  - Security: Fixed inline repository HTTP headers, such as API tokens, being written into `composer.lock` (GHSA-fm2w-xgf2-f9fh)
  - Security: Fixed additional arguments passed to `@composer` scripts not being escaped ([#&#8203;13169](composer/composer#13169))
  - Security: Fixed svn passwords not being redacted from debug output ([#&#8203;13171](composer/composer#13171))
  - Security: Sanitize URL-embedded credentials in hg and fossil error output ([#&#8203;13172](composer/composer#13172))
  - Improved dependency resolution performance and memory usage ([#&#8203;13174](composer/composer#13174))
  - Fixed `config` corrupting composer.json when modifying `extra` or `scripts` entries which are JSON arrays ([#&#8203;13167](composer/composer#13167))
  - Fixed archives not being unwrapped correctly when OS/editor metadata entries like `__MACOSX` or `Thumbs.db` sit next to the package's top-level dir ([#&#8203;13168](composer/composer#13168))
  - Fixed `@script` references with quoted arguments being split on spaces when passed to `@composer` scripts ([#&#8203;13169](composer/composer#13169))

</details>

---

### Configuration

📅 **Schedule**: (UTC)

- Branch creation
  - At any time (no schedule defined)
- Automerge
  - At any time (no schedule defined)

🚦 **Automerge**: Disabled by config. Please merge this manually once you are satisfied.

♻ **Rebasing**: Whenever PR becomes conflicted, or you tick the rebase/retry checkbox.

🔕 **Ignore**: Close this PR and you won't be reminded about this update again.

---

 - [ ] <!-- rebase-check -->If you want to rebase/retry this PR, check this box

---

This PR has been generated by [Mend Renovate](https://github.com/renovatebot/renovate).
<!--renovate-debug:eyJjcmVhdGVkSW5WZXIiOiI0My4yNjAuMCIsInVwZGF0ZWRJblZlciI6IjQzLjI2MC4wIiwidGFyZ2V0QnJhbmNoIjoibWFpbiIsImxhYmVscyI6W119-->

Reviewed-on: https://git.walbeck.it/mwalbeck/docker-composer/pulls/1165
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.

2 participants