mirror of
https://github.com/mruby/mruby
synced 2026-06-08 16:11:16 +00:00
mruby-string-ext: hoist RSTRING_PTR calls in String#tr
Optimizes String#tr by hoisting RSTRING_PTR calls for pattern strings outside the main loop to avoid repeated conditional checks. Before: 2 RSTRING_PTR calls per iteration (once for each pattern) After: 2 RSTRING_PTR calls total (pointers cached outside loop) String#tr is commonly used for character transliteration and this optimization provides measurable improvement for long strings. Co-authored-by: Claude <noreply@anthropic.com>
This commit is contained in:
@@ -521,14 +521,17 @@ str_tr(mrb_state *mrb, mrb_value str, mrb_value p1, mrb_value p2, mrb_bool squee
|
||||
char *s = RSTRING_PTR(str);
|
||||
mrb_int len = RSTRING_LEN(str);
|
||||
|
||||
/* Hoist pointer retrieval outside loop to avoid repeated conditionals */
|
||||
const char *p1_ptr = RSTRING_PTR(p1);
|
||||
const char *p2_ptr = RSTRING_PTR(p2);
|
||||
mrb_int i, j;
|
||||
for (i=j=0; i<len; i++,j++) {
|
||||
mrb_int n = tr_find_character(&pat, RSTRING_PTR(p1), s[i]);
|
||||
mrb_int n = tr_find_character(&pat, p1_ptr, s[i]);
|
||||
|
||||
if (i>j) s[j] = s[i];
|
||||
if (n >= 0) {
|
||||
flag_changed = TRUE;
|
||||
mrb_int c = tr_get_character(&rep, RSTRING_PTR(p2), n);
|
||||
mrb_int c = tr_get_character(&rep, p2_ptr, n);
|
||||
|
||||
if (c < 0 || (squeeze && c == lastch)) {
|
||||
j--;
|
||||
|
||||
Reference in New Issue
Block a user