Skip to content

Commit a043123

Browse files
janbarasekdg
authored andcommitted
Strings: Optimalize strlen() for better performance. (#193)
1 parent 9f9fadd commit a043123

1 file changed

Lines changed: 6 additions & 5 deletions

File tree

src/Utils/Strings.php

Lines changed: 6 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -69,7 +69,7 @@ public static function startsWith(string $haystack, string $needle): bool
6969
*/
7070
public static function endsWith(string $haystack, string $needle): bool
7171
{
72-
return strlen($needle) === 0 || substr($haystack, -strlen($needle)) === $needle;
72+
return $needle === '' || substr($haystack, -strlen($needle)) === $needle;
7373
}
7474

7575

@@ -193,7 +193,7 @@ public static function webalize(string $s, string $charlist = null, bool $lower
193193
public static function truncate(string $s, int $maxLen, string $append = "\u{2026}"): string
194194
{
195195
if (self::length($s) > $maxLen) {
196-
$maxLen = $maxLen - self::length($append);
196+
$maxLen -= self::length($append);
197197
if ($maxLen < 1) {
198198
return $append;
199199

@@ -293,7 +293,8 @@ public static function compare(string $left, string $right, int $len = null): bo
293293
public static function findPrefix(array $strings): string
294294
{
295295
$first = array_shift($strings);
296-
for ($i = 0; $i < strlen($first); $i++) {
296+
$firstLength = strlen($first);
297+
for ($i = 0; $i < $firstLength; $i++) {
297298
foreach ($strings as $s) {
298299
if (!isset($s[$i]) || $first[$i] !== $s[$i]) {
299300
while ($i && $first[$i - 1] >= "\x80" && $first[$i] >= "\x80" && $first[$i] < "\xC0") {
@@ -406,7 +407,7 @@ private static function pos(string $haystack, string $needle, int $nth = 1): ?in
406407
if (!$nth) {
407408
return null;
408409
} elseif ($nth > 0) {
409-
if (strlen($needle) === 0) {
410+
if ($needle === '') {
410411
return 0;
411412
}
412413
$pos = 0;
@@ -415,7 +416,7 @@ private static function pos(string $haystack, string $needle, int $nth = 1): ?in
415416
}
416417
} else {
417418
$len = strlen($haystack);
418-
if (strlen($needle) === 0) {
419+
if ($needle === '') {
419420
return $len;
420421
}
421422
$pos = $len - 1;

0 commit comments

Comments
 (0)