From 7e26271a01fa807742a5dfc8ae07a87d7b304801 Mon Sep 17 00:00:00 2001 From: "Yukihiro \"Matz\" Matsumoto" Date: Wed, 22 Oct 2025 09:13:00 +0900 Subject: [PATCH] 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 --- mrbgems/mruby-string-ext/src/string.c | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/mrbgems/mruby-string-ext/src/string.c b/mrbgems/mruby-string-ext/src/string.c index fa22d397d..b0b90add2 100644 --- a/mrbgems/mruby-string-ext/src/string.c +++ b/mrbgems/mruby-string-ext/src/string.c @@ -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; ij) 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--;