From 13e63657a495c465b1780b5e056dd03a5f16642e Mon Sep 17 00:00:00 2001 From: "Yukihiro \"Matz\" Matsumoto" Date: Mon, 23 Mar 2026 09:37:58 +0900 Subject: [PATCH] mruby-regexp: use array join in __sub_replace to avoid O(n^2) Same pattern as the earlier gsub fix: collect parts in an array and join at the end instead of repeated string concatenation. Co-authored-by: Claude --- mrbgems/mruby-regexp/mrblib/string_regexp.rb | 23 ++++++++++---------- 1 file changed, 11 insertions(+), 12 deletions(-) diff --git a/mrbgems/mruby-regexp/mrblib/string_regexp.rb b/mrbgems/mruby-regexp/mrblib/string_regexp.rb index ad7df6e33..80e9435ef 100644 --- a/mrbgems/mruby-regexp/mrblib/string_regexp.rb +++ b/mrbgems/mruby-regexp/mrblib/string_regexp.rb @@ -15,37 +15,36 @@ class String def __sub_replace(rep, md) return rep unless rep.include?("\\") - result = "" + parts = [] i = 0 while i < rep.length if rep[i] == "\\" && i + 1 < rep.length c = rep[i + 1] case c when '0'..'9' - result += (md[c.to_i] || "") + parts << (md[c.to_i] || "") when '&' - result += (md[0] || "") + parts << (md[0] || "") when '`' - result += md.pre_match + parts << md.pre_match when "'" - result += md.post_match + parts << md.post_match when '+' - # last successful capture last = nil - md.captures.each { |c| last = c if c } - result += (last || "") + md.captures.each { |v| last = v if v } + parts << (last || "") when "\\" - result += "\\" + parts << "\\" else - result += "\\" + c + parts << "\\" << c end i += 2 else - result += rep[i] + parts << rep[i] i += 1 end end - result + parts.join end def sub(pattern, replacement = nil, &block)