Commit c9a55e07

c9a55e07391eMerged

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

Description

perf: generalize concat chain flattening to N parts (sp_str_concat_arr)

The concat flattening previously capped at 4 parts, leaving longer chains like csv_process's 7-part line builder using partial specialization (1 concat4 + 3 concat = 4 malloc'd strings).

Add sp_str_concat_arr(parts, n) that does a single malloc for any number of parts, using a C99 compound-literal array at the call site. Raise the codegen cap to 12 parts (generous).

csv_process: 224ms → 221ms (marginal, since the long-chain line generation is outside the hot 200× loop). Other benchmarks unchanged (no chains ≥ 5 parts).

75/75 tests, bootstrap stable, 52 benchmarks pass.

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

Details

Commit
c9a55e07391e
Parent
782b19ccd068

lib/sp_runtime.hmodifiedView file

@@ -255,6 +255,8 @@
255255 static const char*sp_str_concat(const char*a,const char*b){size_t la=strlen(a),lb=strlen(b);char*r=(char*)malloc(1+la+lb+1);r[0]=(char)0xff;memcpy(r+1,a,la);memcpy(r+1+la,b,lb);r[1+la+lb]=0;return r+1;}
256256 static const char*sp_str_concat3(const char*a,const char*b,const char*c){size_t la=strlen(a),lb=strlen(b),lc=strlen(c);char*r=(char*)malloc(1+la+lb+lc+1);r[0]=(char)0xff;memcpy(r+1,a,la);memcpy(r+1+la,b,lb);memcpy(r+1+la+lb,c,lc+1);return r+1;}
257257 static const char*sp_str_concat4(const char*a,const char*b,const char*c,const char*d){size_t la=strlen(a),lb=strlen(b),lc=strlen(c),ld=strlen(d);char*r=(char*)malloc(1+la+lb+lc+ld+1);r[0]=(char)0xff;memcpy(r+1,a,la);memcpy(r+1+la,b,lb);memcpy(r+1+la+lb,c,lc);memcpy(r+1+la+lb+lc,d,ld+1);return r+1;}
258+/* Concatenate N strings in a single malloc. */
259+static const char*sp_str_concat_arr(const char *const *parts,int n){size_t total=0;for(int i=0;i<n;i++)total+=strlen(parts[i]);char*r=(char*)malloc(1+total+1);r[0]=(char)0xff;char*p=r+1;for(int i=0;i<n;i++){size_t sl=strlen(parts[i]);memcpy(p,parts[i],sl);p+=sl;}*p=0;return r+1;}
258260 static const char*sp_int_to_s(mrb_int n){char*b=sp_str_alloc_raw(32);snprintf(b,32,"%lld",(long long)n);return b;}
259261 static const char*sp_int_to_s_base(mrb_int n,mrb_int base){if(base<2||base>36)base=10;char*b=sp_str_alloc_raw(72);char tmp[72];int i=0;int neg=0;uint64_t u;if(n<0){neg=1;u=(uint64_t)(-(n+1))+1;}else{u=(uint64_t)n;}if(u==0){tmp[i++]='0';}else{while(u>0){mrb_int d=u%base;tmp[i++]=d<10?'0'+d:'a'+d-10;u/=base;}}int j=0;if(neg)b[j++]='-';while(i>0)b[j++]=tmp[--i];b[j]=0;return b;}
260262 static const char*sp_float_to_s(mrb_float f){char*b=sp_str_alloc_raw(64);snprintf(b,64,"%g",f);return b;}