Skip to content

Commit b51cb93

Browse files
perf: optimize loop performance by pre-calculating array counts in Str::apa() and fileSize() methods (#56796)
* Refactor: Pre-calculate array counts before loops This commit optimizes loops within the `Str::apa` and `Number::fileSize` methods by pre-calculating the array count and storing it in a variable. Previously, the `count()` function was called on each iteration, leading to minor performance overhead. This change avoids these redundant function calls. * This commit perform static analysis and improve overall code quality. As an initial application of the tool, the `Number::fileSize` method has been refactored for performance. The array count is now cached in a variable before the loop to avoid calling `count()` on every iteration. * Formatting --------- Co-authored-by: Taylor Otwell <taylor@laravel.com>
1 parent 77f90cb commit b51cb93

File tree

2 files changed

+5
-2
lines changed

2 files changed

+5
-2
lines changed

src/Illuminate/Support/Number.php

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -207,7 +207,9 @@ public static function fileSize(int|float $bytes, int $precision = 0, ?int $maxP
207207
{
208208
$units = ['B', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'];
209209

210-
for ($i = 0; ($bytes / 1024) > 0.9 && ($i < count($units) - 1); $i++) {
210+
$unitCount = count($units);
211+
212+
for ($i = 0; ($bytes / 1024) > 0.9 && ($i < $unitCount - 1); $i++) {
211213
$bytes /= 1024;
212214
}
213215

src/Illuminate/Support/Str.php

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1458,8 +1458,9 @@ public static function apa($value)
14581458
$endPunctuation = ['.', '!', '?', ':', '', ','];
14591459

14601460
$words = mb_split('\s+', $value);
1461+
$wordCount = count($words);
14611462

1462-
for ($i = 0; $i < count($words); $i++) {
1463+
for ($i = 0; $i < $wordCount; $i++) {
14631464
$lowercaseWord = mb_strtolower($words[$i]);
14641465

14651466
if (str_contains($lowercaseWord, '-')) {

0 commit comments

Comments
 (0)