Skip to content

Commit 8ca3fe5

Browse files
authored
ext/standard: Optimize pack() by avoiding redundant padding in pack() string formats (#24133)
1 parent 6121203 commit 8ca3fe5

2 files changed

Lines changed: 8 additions & 3 deletions

File tree

‎UPGRADING‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -99,6 +99,8 @@ PHP 8.7 UPGRADE NOTES
9999
. Improved performance of array_splice() when inserting without removing
100100
elements.
101101
. Improved performance of str_rot13().
102+
. Improved performance of pack() for large strings using the a, A and Z
103+
formats.
102104

103105
- MBString:
104106
. Improved performance of mb_strlen for UTF-8 strings.

‎ext/standard/pack.c‎

Lines changed: 6 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -559,9 +559,12 @@ PHP_FUNCTION(pack)
559559
zend_string *tmp_str;
560560
zend_string *str = zval_get_tmp_string(&argv[currentarg++], &tmp_str);
561561

562-
memset(&ZSTR_VAL(output)[outputpos], (code == 'a' || code == 'Z') ? '\0' : ' ', arg);
563-
memcpy(&ZSTR_VAL(output)[outputpos], ZSTR_VAL(str),
564-
(ZSTR_LEN(str) < arg_cp) ? ZSTR_LEN(str) : arg_cp);
562+
arg_cp = MIN(ZSTR_LEN(str), arg_cp);
563+
if (arg_cp < arg) {
564+
memset(&ZSTR_VAL(output)[outputpos + arg_cp],
565+
(code == 'a' || code == 'Z') ? '\0' : ' ', arg - arg_cp);
566+
}
567+
memcpy(&ZSTR_VAL(output)[outputpos], ZSTR_VAL(str), arg_cp);
565568

566569
outputpos += arg;
567570
zend_tmp_string_release(tmp_str);

0 commit comments

Comments
 (0)