Skip to content

Instantly share code, notes, and snippets.

@derhansen
Created January 20, 2024 13:59
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save derhansen/e0751d896ba0d48917dccd44bd4e4d1e to your computer and use it in GitHub Desktop.
Save derhansen/e0751d896ba0d48917dccd44bd4e4d1e to your computer and use it in GitHub Desktop.
TYPO3 GeneralUtility::intExplode() performance test
<?php
// Current intExplode function in v13
function intExplodeOld($delimiter, $string, $removeEmptyValues = false)
{
$result = explode($delimiter, $string);
foreach ($result as $key => &$value) {
if ($removeEmptyValues && trim($value) === '') {
unset($result[$key]);
} else {
$value = (int)$value;
}
}
unset($value);
/** @var array<int, int> $result */
return $result;
}
// New intExplode function refactored to use `array_filter` and `array_walk`
function intExplodeNew($delimiter, $string, $removeEmptyValues = false)
{
$result = explode($delimiter, $string);
if ($removeEmptyValues) {
$result = array_filter($result, static function (mixed $value): bool {
return trim($value) !== '';
});
}
array_walk($result, static function (mixed &$value): void {
$value = (int)$value;
});
// This is faster as `array_walk`, but still a factor ~3 slower than the original
// $result = array_map(intval(...), $result);
/** @var array<int, int> $result */
return $result;
}
$stringToExplode = '';
for ($i = 1; $i <= 1000000; $i++) {
$stringToExplode .= $i . ',';
}
$timeStart = microtime(true);
intExplodeOld(',', $stringToExplode, true);
$timeEnd = microtime(true);
$executionTime = $timeEnd - $timeStart;
echo('Old: ' . $executionTime . PHP_EOL);
$timeStart = microtime(true);
intExplodeNew(',', $stringToExplode, true);
$timeEnd = microtime(true);
$executionTime = $timeEnd - $timeStart;
echo('New: ' . $executionTime . PHP_EOL);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment