Skip to content

Commit ba1eb4c

Browse files
Optimize performances of str_pad()
1 parent ff810d5 commit ba1eb4c

File tree

1 file changed

+29
-5
lines changed

1 file changed

+29
-5
lines changed

ext/standard/string.c

Lines changed: 29 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -5737,6 +5737,26 @@ PHP_FUNCTION(substr_count)
57375737
}
57385738
/* }}} */
57395739

5740+
static zend_always_inline void php_str_pad_fill(zend_string *result, size_t pad_chars, const char *pad_str, size_t pad_str_len) {
5741+
char *dest = ZSTR_VAL(result) + ZSTR_LEN(result);
5742+
5743+
if (pad_str_len == 1) {
5744+
memset(dest, pad_str[0], pad_chars);
5745+
return;
5746+
}
5747+
5748+
char *p = dest;
5749+
const char *end = dest + pad_chars;
5750+
5751+
while (p + pad_str_len <= end) {
5752+
p = zend_mempcpy(p, pad_str, pad_str_len);
5753+
}
5754+
5755+
if (p < end) {
5756+
memcpy(p, pad_str, end - p);
5757+
}
5758+
}
5759+
57405760
/* {{{ Returns input string padded on the left or right to specified length with pad_string */
57415761
PHP_FUNCTION(str_pad)
57425762
{
@@ -5749,7 +5769,7 @@ PHP_FUNCTION(str_pad)
57495769
char *pad_str = " "; /* Pointer to padding string */
57505770
size_t pad_str_len = 1;
57515771
zend_long pad_type_val = PHP_STR_PAD_RIGHT; /* The padding type value */
5752-
size_t i, left_pad=0, right_pad=0;
5772+
size_t left_pad=0, right_pad=0;
57535773
zend_string *result = NULL; /* Resulting string */
57545774

57555775
ZEND_PARSE_PARAMETERS_START(2, 4)
@@ -5799,16 +5819,20 @@ PHP_FUNCTION(str_pad)
57995819
}
58005820

58015821
/* First we pad on the left. */
5802-
for (i = 0; i < left_pad; i++)
5803-
ZSTR_VAL(result)[ZSTR_LEN(result)++] = pad_str[i % pad_str_len];
5822+
if (left_pad > 0) {
5823+
php_str_pad_fill(result, left_pad, pad_str, pad_str_len);
5824+
ZSTR_LEN(result) += left_pad;
5825+
}
58045826

58055827
/* Then we copy the input string. */
58065828
memcpy(ZSTR_VAL(result) + ZSTR_LEN(result), ZSTR_VAL(input), ZSTR_LEN(input));
58075829
ZSTR_LEN(result) += ZSTR_LEN(input);
58085830

58095831
/* Finally, we pad on the right. */
5810-
for (i = 0; i < right_pad; i++)
5811-
ZSTR_VAL(result)[ZSTR_LEN(result)++] = pad_str[i % pad_str_len];
5832+
if (right_pad > 0) {
5833+
php_str_pad_fill(result, right_pad, pad_str, pad_str_len);
5834+
ZSTR_LEN(result) += right_pad;
5835+
}
58125836

58135837
ZSTR_VAL(result)[ZSTR_LEN(result)] = '\0';
58145838

0 commit comments

Comments
 (0)