Skip to content

Commit fbfa654

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

File tree

1 file changed

+30
-5
lines changed

1 file changed

+30
-5
lines changed

ext/standard/string.c

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

5740+
static inline void php_str_pad_fill(char *dest, size_t pad_chars, const char *pad_str, size_t pad_str_len) {
5741+
if (pad_str_len == 1) {
5742+
memset(dest, pad_str[0], pad_chars);
5743+
5744+
return;
5745+
}
5746+
5747+
size_t full_copies = pad_chars / pad_str_len;
5748+
size_t remainder = pad_chars % pad_str_len;
5749+
char *p = dest;
5750+
5751+
for (size_t j = 0; j < full_copies; ++j) {
5752+
memcpy(p, pad_str, pad_str_len);
5753+
p += pad_str_len;
5754+
}
5755+
5756+
if (remainder > 0) {
5757+
memcpy(p, pad_str, remainder);
5758+
}
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,20 @@ 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(ZSTR_VAL(result) + ZSTR_LEN(result), left_pad, pad_str, pad_str_len);
5825+
ZSTR_LEN(result) += left_pad;
5826+
}
58045827

58055828
/* Then we copy the input string. */
58065829
memcpy(ZSTR_VAL(result) + ZSTR_LEN(result), ZSTR_VAL(input), ZSTR_LEN(input));
58075830
ZSTR_LEN(result) += ZSTR_LEN(input);
58085831

58095832
/* 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];
5833+
if (right_pad > 0) {
5834+
php_str_pad_fill(ZSTR_VAL(result) + ZSTR_LEN(result), right_pad, pad_str, pad_str_len);
5835+
ZSTR_LEN(result) += right_pad;
5836+
}
58125837

58135838
ZSTR_VAL(result)[ZSTR_LEN(result)] = '\0';
58145839

0 commit comments

Comments
 (0)