Commit 85036c4c

85036c4ce95dMerged

Yukihiro "Matz" Matsumoto <[email protected]> · 7 months ago · 2 files · ~2 modified

Description

perf: extend strlen hoisting to sp_str_sub_range calls

When strlen is hoisted out of a while loop for condition check, propagate it to string [] operations on the same receiver via a new sp_str_sub_range_len(s, len, start, n) variant.

Key fix: compile_while_stmt now saves and restores the hoist state around nested loops. Previously the inner loop's cleanup clobbered the outer loop's hoist, making the outer receiver's length hoist ineffective for body code after the inner loop.

template: 140ms → 136ms (-3%), strlen 13.6%→8.2% of instructions json_parse: 41ms → 37ms (-10%)

Remaining strlen cost is from sp_str_concat(result, x) where result is a growing mutable string — can't be hoisted.

75/75 tests, bootstrap stable.

Co-Authored-By: Claude Opus 4.6 (1M context) [email protected]

Details

Commit
85036c4ce95d
Parent
efe0e6e2f9ed

lib/sp_runtime.hmodifiedView file

@@ -278,6 +278,9 @@
278278 static char sp_char_cache[256][3];
279279 static int sp_char_cache_init = 0;
280280 static const char*sp_str_sub_range(const char*s,mrb_int start,mrb_int len){mrb_int sl=(mrb_int)strlen(s);if(start<0)start+=sl;if(start<0)start=0;if(start>=sl)return ("\xff" "" + 1);if(len<0)len=0;if(start+len>sl)len=sl-start;if(len==1){unsigned char c=(unsigned char)s[start];if(!sp_char_cache_init){for(int i=0;i<256;i++){sp_char_cache[i][0]=(char)0xff;sp_char_cache[i][1]=(char)i;sp_char_cache[i][2]=0;}sp_char_cache_init=1;}return &sp_char_cache[c][1];}char*r=sp_str_alloc_raw(len+1);memcpy(r,s+start,len);r[len]=0;return r;}
281+/* Same as sp_str_sub_range but caller provides the string length
282+ (useful when strlen has been hoisted out of a loop). */
283+static const char*sp_str_sub_range_len(const char*s,mrb_int sl,mrb_int start,mrb_int len){if(start<0)start+=sl;if(start<0)start=0;if(start>=sl)return ("\xff" "" + 1);if(len<0)len=0;if(start+len>sl)len=sl-start;if(len==1){unsigned char c=(unsigned char)s[start];if(!sp_char_cache_init){for(int i=0;i<256;i++){sp_char_cache[i][0]=(char)0xff;sp_char_cache[i][1]=(char)i;sp_char_cache[i][2]=0;}sp_char_cache_init=1;}return &sp_char_cache[c][1];}char*r=sp_str_alloc_raw(len+1);memcpy(r,s+start,len);r[len]=0;return r;}
281284 static const char*sp_sprintf(const char*fmt,...){char*b=sp_str_alloc_raw(4096);va_list ap;va_start(ap,fmt);vsnprintf(b,4096,fmt,ap);va_end(ap);return b;}
282285 static const char*sp_str_reverse(const char*s){size_t l=strlen(s);char*r=sp_str_alloc_raw(l+1);for(size_t i=0;i<l;i++)r[i]=s[l-1-i];r[l]=0;return r;}
283286 static const char*sp_str_sub(const char*s,const char*pat,const char*rep){const char*f=strstr(s,pat);if(!f)return s;size_t pl=strlen(pat),rl=strlen(rep),sl=strlen(s);char*r=sp_str_alloc_raw(sl-pl+rl+1);size_t n=f-s;memcpy(r,s,n);memcpy(r+n,rep,rl);memcpy(r+n+rl,f+pl,sl-n-pl+1);return r;}