Skip to content

Commit 78dd005

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

File tree

1 file changed

+28
-5
lines changed

1 file changed

+28
-5
lines changed

ext/standard/string.c

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

5740+
static void php_str_pad_fill(zend_string *result, size_t pad_chars, const char *pad_str, size_t pad_str_len) {
5741+
char *p = ZSTR_VAL(result) + ZSTR_LEN(result);
5742+
5743+
if (pad_str_len == 1) {
5744+
memset(p, pad_str[0], pad_chars);
5745+
ZSTR_LEN(result) += pad_chars;
5746+
return;
5747+
}
5748+
5749+
const char *end = p + pad_chars;
5750+
while (p + pad_str_len <= end) {
5751+
p = zend_mempcpy(p, pad_str, pad_str_len);
5752+
}
5753+
5754+
if (p < end) {
5755+
memcpy(p, pad_str, end - p);
5756+
}
5757+
5758+
ZSTR_LEN(result) += pad_chars;
5759+
}
5760+
57405761
/* {{{ Returns input string padded on the left or right to specified length with pad_string */
57415762
PHP_FUNCTION(str_pad)
57425763
{
@@ -5749,7 +5770,7 @@ PHP_FUNCTION(str_pad)
57495770
char *pad_str = " "; /* Pointer to padding string */
57505771
size_t pad_str_len = 1;
57515772
zend_long pad_type_val = PHP_STR_PAD_RIGHT; /* The padding type value */
5752-
size_t i, left_pad=0, right_pad=0;
5773+
size_t left_pad=0, right_pad=0;
57535774
zend_string *result = NULL; /* Resulting string */
57545775

57555776
ZEND_PARSE_PARAMETERS_START(2, 4)
@@ -5799,16 +5820,18 @@ PHP_FUNCTION(str_pad)
57995820
}
58005821

58015822
/* 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];
5823+
if (left_pad > 0) {
5824+
php_str_pad_fill(result, left_pad, pad_str, pad_str_len);
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+
}
58125835

58135836
ZSTR_VAL(result)[ZSTR_LEN(result)] = '\0';
58145837

0 commit comments

Comments
 (0)