From db0a4d9045892e9f8b5760267dc80ff51cac4d22 Mon Sep 17 00:00:00 2001 From: KOBAYASHI Shuji Date: Sat, 26 Oct 2019 22:19:04 +0900 Subject: Optimize `chars2bytes` with `MRB_UTF8_STRING` to ASCII only string ### Benchmark (with `MRB_UTF8_STRING`) ``` $ mruby -e ' COUNT = 150000 SIZE = 10000 strs = Array.new(COUNT) do s = "a" * SIZE s.size # set `MRB_STR_ASCII` flag s end i = 0 t = Time.now while i < COUNT strs[i][-2..-1] = "" i += 1 end printf "%.2f sec\n", Time.now - t ' 1.10 sec # before 0.07 sec # after ``` --- src/string.c | 23 ++++++++++++++--------- 1 file changed, 14 insertions(+), 9 deletions(-) (limited to 'src/string.c') diff --git a/src/string.c b/src/string.c index 518b62ea3..e5c3a3843 100644 --- a/src/string.c +++ b/src/string.c @@ -330,16 +330,21 @@ utf8_strlen(mrb_value str) static mrb_int chars2bytes(mrb_value s, mrb_int off, mrb_int idx) { - mrb_int i, b, n; - const char *p = RSTRING_PTR(s) + off; - const char *e = RSTRING_END(s); + if (RSTR_ASCII_P(mrb_str_ptr(s))) { + return idx; + } + else { + mrb_int i, b, n; + const char *p = RSTRING_PTR(s) + off; + const char *e = RSTRING_END(s); - for (b=i=0; p