Skip to content

Commit cddbb98

Browse files
committed
strtr() with 2nd param array - optimization
About a 1.25x speedup in my test script by writing the result string only when a match is found and at the end instead of on each iteration.
1 parent 2111ee3 commit cddbb98

File tree

1 file changed

+5
-6
lines changed

1 file changed

+5
-6
lines changed

ext/standard/string.c

Lines changed: 5 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -3028,6 +3028,7 @@ static void php_strtr_array_destroy_ppres(PPRES *d)
30283028
static void php_strtr_array_do_repl(STR *text, PPRES *d, zval *return_value)
30293029
{
30303030
STRLEN pos = 0,
3031+
nextwpos = 0,
30313032
lastpos = L(text) - d->m;
30323033
smart_str result = {0};
30333034

@@ -3036,7 +3037,6 @@ static void php_strtr_array_do_repl(STR *text, PPRES *d, zval *return_value)
30363037
STRLEN shift = d->shift->entries[h];
30373038

30383039
if (shift > 0) {
3039-
smart_str_appendl(&result, &S(text)[pos], MIN(shift, L(text) - pos));
30403040
pos += shift;
30413041
} else {
30423042
HASH h2 = h & d->hash->table_mask,
@@ -3056,20 +3056,19 @@ static void php_strtr_array_do_repl(STR *text, PPRES *d, zval *return_value)
30563056
memcmp(S(&pnr->pat), &S(text)[pos], L(&pnr->pat)) != 0)
30573057
continue;
30583058

3059-
smart_str_appendl(&result, S(&pnr->repl), (int)L(&pnr->repl));
3059+
smart_str_appendl(&result, &S(text)[nextwpos], pos - nextwpos);
3060+
smart_str_appendl(&result, S(&pnr->repl), L(&pnr->repl));
30603061
pos += L(&pnr->pat);
3062+
nextwpos = pos;
30613063
goto end_outer_loop;
30623064
}
30633065

3064-
smart_str_appendc(&result, S(text)[pos]);
30653066
pos++;
30663067
end_outer_loop: ;
30673068
}
30683069
}
30693070

3070-
if (pos < L(text)) {
3071-
smart_str_appendl(&result, &S(text)[pos], (int)(L(text) - pos));
3072-
}
3071+
smart_str_appendl(&result, &S(text)[nextwpos], L(text) - nextwpos);
30733072

30743073
if (result.c != NULL) {
30753074
smart_str_0(&result);

0 commit comments

Comments
 (0)