Skip to content

[OptionsResolver] Optimize splitOutsideParenthesis() - 2.91x faster #61239

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 1 commit into
base: 7.4
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
42 changes: 26 additions & 16 deletions src/Symfony/Component/OptionsResolver/OptionsResolver.php
Original file line number Diff line number Diff line change
Expand Up @@ -1215,30 +1215,40 @@ private function verifyTypes(string $type, mixed $value, ?array &$invalidTypes =
*/
private function splitOutsideParenthesis(string $type): array
{
if (!str_contains($type, '|')) {
Copy link
Member

@dunglas dunglas Jul 26, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Maybe could we even store a hardcoded list of known simple types somewhere to avoid the repeated calls to str_contains() in these cases.

Here is a list: https://www.php.net/manual/en/function.gettype.php

return [$type];
}

if (!str_contains($type, '(') && !str_contains($type, ')')) {
Copy link
Member

@dunglas dunglas Jul 26, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We could likely optimize that too by looping over characters and check for both parenthesis. This will prevent looping two times.

A regexp to avoid the two calls to str_contains() may also be faster than the current implementation (but slower that the loop I propose).

return explode('|', $type);
}

$parts = [];
$currentPart = '';
$start = 0;
$parenthesisLevel = 0;
$length = \strlen($type);

$typeLength = \strlen($type);
for ($i = 0; $i < $typeLength; ++$i) {
for ($i = 0; $i < $length; ++$i) {
$char = $type[$i];

if ('(' === $char) {
++$parenthesisLevel;
} elseif (')' === $char) {
--$parenthesisLevel;
}

if ('|' === $char && 0 === $parenthesisLevel) {
$parts[] = $currentPart;
$currentPart = '';
} else {
$currentPart .= $char;
switch ($char) {
case '(':
++$parenthesisLevel;
break;
case ')':
--$parenthesisLevel;
break;
case '|':
if (0 === $parenthesisLevel) {
$parts[] = substr($type, $start, $i - $start);
$start = $i + 1;
}
break;
}
}

if ('' !== $currentPart) {
$parts[] = $currentPart;
if ($start < $length) {
$parts[] = substr($type, $start);
}

return $parts;
Expand Down
Loading