Commit b431d906

b431d9064257Merged

Yukihiro "Matz" Matsumoto <[email protected]> · 6 months ago · 1 file · ~1 modified

Description

perf(runtime): cache char_len per string for O(1) length / byte_offset

Profile of bm_json_parse on the spinel binary showed 55% of cycles in sp_str_length and 24% in sp_utf8_byte_offset (plus 9% in libc strlen they call through sp_str_byte_len). Both functions did a full per-character UTF-8 walk every call, so a tight loop like

while @pos < @input.length c = @input[@pos] ... end

scanned the same 82-byte JSON literal once per outer length call and once per indexed access, plus a fresh strlen every time because the literal carries the 0xff "rodata" marker that bypasses the heap header's cached byte length.

The fix is a 32-slot direct-mapped pointer-keyed cache mapping each string pointer to its (byte_len, char_len). sp_str_length populates the cache on the first call; sp_utf8_byte_offset reads it and takes an O(1) shortcut when char_len == byte_len (the string is pure ASCII, so byte offset equals character index). Both calls also share a new sp_str_count_chars helper whose 8-byte ASCII-detect prologue keeps the cold-path cost low for any-ascii prefixes.

Cache invariants:

  • Cleared in sp_str_sweep so a freed-and-reused heap address can never serve a stale entry from a previous owner.
  • Skipped for sp_String wrapper bodies (marker 0xfd) whose buffer can move on append/prepend.
  • Per-translation-unit (static in the header). The only callers of sp_str_length / sp_utf8_byte_offset are the generated user program; the runtime archive (regexp, bigint, crypto) does not call them, so there is no cross-TU cache fragmentation.

Bench impact (Ruby 4.0.4 +YJIT baseline, best-of-3):

  • json_parse 296 -> 48 ms (-84%, vs YJIT 0.93x -> 5.7x)
  • huffman 17 -> 8 ms (-53%)
  • template 275 -> 175 ms (-36%)
  • fasta 3 -> 2 ms (-33%)
  • splay tree 15 -> 14 ms
  • fib 16 -> 15 ms

Geometric mean across the 28 README benchmarks: 6.83x -> 7.52x vs YJIT. No other benchmark moves beyond noise floor (+/-1 ms on cells already under 10 ms). 579 tests pass; optcarrot still hits the canonical 59662 checksum at fps 654.

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

Details

Commit
b431d9064257
Parent
238a05638400

lib/sp_runtime.hmodifiedView file

@@ -276,7 +276,63 @@
276276 static inline int sp_utf8_advance(const char*p){int cn=sp_utf8_char_len((unsigned char)*p);int i=1;while(i<cn&&((unsigned char)p[i]&0xC0)==0x80)i++;return i;}
277277 static inline int sp_utf8_decode(const char*p,uint32_t*out){unsigned char c=(unsigned char)p[0];if(c<0x80){*out=c;return 1;}if(c<0xC0){*out=c;return 1;}unsigned char c1=(unsigned char)p[1];if((c1&0xC0)!=0x80){*out=c;return 1;}if(c<0xE0){*out=((uint32_t)(c&0x1F)<<6)|(c1&0x3F);return 2;}unsigned char c2=(unsigned char)p[2];if((c2&0xC0)!=0x80){*out=c;return 1;}if(c<0xF0){*out=((uint32_t)(c&0x0F)<<12)|((uint32_t)(c1&0x3F)<<6)|(c2&0x3F);return 3;}unsigned char c3=(unsigned char)p[3];if((c3&0xC0)!=0x80){*out=c;return 1;}*out=((uint32_t)(c&0x07)<<18)|((uint32_t)(c1&0x3F)<<12)|((uint32_t)(c2&0x3F)<<6)|(c3&0x3F);return 4;}
278278 static inline int sp_utf8_encode(uint32_t cp,char*out){if(cp<0x80){out[0]=(char)cp;return 1;}if(cp<0x800){out[0]=(char)(0xC0|(cp>>6));out[1]=(char)(0x80|(cp&0x3F));return 2;}if(cp<0x10000){out[0]=(char)(0xE0|(cp>>12));out[1]=(char)(0x80|((cp>>6)&0x3F));out[2]=(char)(0x80|(cp&0x3F));return 3;}out[0]=(char)(0xF0|(cp>>18));out[1]=(char)(0x80|((cp>>12)&0x3F));out[2]=(char)(0x80|((cp>>6)&0x3F));out[3]=(char)(0x80|(cp&0x3F));return 4;}
279-static mrb_int sp_str_length(const char*s){size_t bl=sp_str_byte_len(s);const char*end=s+bl;mrb_int n=0;while(s<end){s+=sp_utf8_advance(s);n++;}return n;}
279+/* Direct-mapped pointer-keyed cache for (byte_len, char_len). Populated lazily
280+ by sp_str_length / sp_utf8_byte_offset; the same entries unlock both calls
281+ so iterating a single string with `s.length` + `s[i]` walks UTF-8 once
282+ instead of per access. ASCII strings (char_len == byte_len) take an O(1)
283+ byte_offset fast path. Cleared by sp_str_sweep so freed-and-reused heap
284+ addresses can't leak stale entries. Skipped for sp_String wrappers (marker
285+ 0xfd) whose buffers can move on realloc. */
286+#define SP_STR_LCACHE_BITS 5
287+#define SP_STR_LCACHE_SIZE (1u << SP_STR_LCACHE_BITS)
288+static struct sp_str_lcache_entry {
289+ const char *s;
290+ size_t byte_len;
291+ mrb_int char_len;
292+} sp_str_lcache[SP_STR_LCACHE_SIZE];
293+
294+static inline unsigned sp_str_lcache_hash(const char *s) {
295+ uintptr_t k = (uintptr_t)s;
296+ return (unsigned)((k ^ (k >> 4) ^ (k >> 12)) & (SP_STR_LCACHE_SIZE - 1));
297+}
298+
299+static inline void sp_str_lcache_clear(void) {
300+ for (unsigned i = 0; i < SP_STR_LCACHE_SIZE; i++) sp_str_lcache[i].s = NULL;
301+}
302+
303+/* Count UTF-8 code points in s[0..bl). The 8-byte ASCII-detect prologue skips
304+ bytes 8 at a time while the high bit stays clear, so pure-ASCII strings (the
305+ common case in the JSON / CSV / template benchmarks) run vastly faster than
306+ the per-byte advance loop they used to fall through. */
307+static mrb_int sp_str_count_chars(const char *s, size_t bl) {
308+ const char *p = s, *end = s + bl;
309+ mrb_int n = 0;
310+ while (p + 8 <= end) {
311+ uint64_t w;
312+ memcpy(&w, p, sizeof(w));
313+ if (w & 0x8080808080808080ULL) break;
314+ p += 8; n += 8;
315+ }
316+ while (p < end) {
317+ if ((unsigned char)*p < 0x80) { p++; n++; }
318+ else { p += sp_utf8_advance(p); n++; }
319+ }
320+ return n;
321+}
322+
323+static mrb_int sp_str_length(const char*s){
324+ if (!s) return 0;
325+ unsigned char m = ((const unsigned char *)s)[-1];
326+ if (m == 0xfd) return sp_str_count_chars(s, sp_str_byte_len(s));
327+ unsigned h = sp_str_lcache_hash(s);
328+ if (sp_str_lcache[h].s == s) return sp_str_lcache[h].char_len;
329+ size_t bl = sp_str_byte_len(s);
330+ mrb_int n = sp_str_count_chars(s, bl);
331+ sp_str_lcache[h].s = s;
332+ sp_str_lcache[h].byte_len = bl;
333+ sp_str_lcache[h].char_len = n;
334+ return n;
335+}
280336 static mrb_int sp_str_ord(const char*s){if(!*s)return 0;uint32_t cp;sp_utf8_decode(s,&cp);return(mrb_int)cp;}
281337 /* NULL-safe string equality. ENV[] returns NULL for unset vars
282338 (the dispatch is `sp_str_dup_external(getenv(...))`, which propagates
@@ -285,7 +341,19 @@
285341 Ruby; nil == nil is true, so falling back to pointer equality on the
286342 NULL path covers both. */
287343 static inline int sp_str_eq(const char*a,const char*b){if(!a||!b)return a==b;return strcmp(a,b)==0;}
288-static size_t sp_utf8_byte_offset(const char*s,mrb_int char_idx){size_t bl=sp_str_byte_len(s);const char*p=s;const char*end=s+bl;while(char_idx>0&&p<end){p+=sp_utf8_advance(p);char_idx--;}return(size_t)(p-s);}
344+static size_t sp_utf8_byte_offset(const char*s,mrb_int char_idx){
345+ if (!s || char_idx <= 0) return 0;
346+ unsigned char m = ((const unsigned char *)s)[-1];
347+ if (m != 0xfd) {
348+ unsigned h = sp_str_lcache_hash(s);
349+ if (sp_str_lcache[h].s == s
350+ && (size_t)sp_str_lcache[h].char_len == sp_str_lcache[h].byte_len) {
351+ size_t off = (size_t)char_idx;
352+ return off > sp_str_lcache[h].byte_len ? sp_str_lcache[h].byte_len : off;
353+ }
354+ }
355+ size_t bl=sp_str_byte_len(s);const char*p=s;const char*end=s+bl;while(char_idx>0&&p<end){p+=sp_utf8_advance(p);char_idx--;}return(size_t)(p-s);
356+}
289357 static uint32_t*sp_utf8_decode_all(const char*s,size_t*out_n){size_t cap=8,n=0;uint32_t*cps=(uint32_t*)malloc(cap*sizeof(uint32_t));const char*p=s;while(*p){if(n>=cap){cap*=2;cps=(uint32_t*)realloc(cps,cap*sizeof(uint32_t));}uint32_t cp;p+=sp_utf8_decode(p,&cp);cps[n++]=cp;}*out_n=n;return cps;}
290358 static int sp_utf8_set_has(const uint32_t*cps,size_t n,uint32_t cp){for(size_t i=0;i<n;i++)if(cps[i]==cp)return 1;return 0;}
291359
@@ -311,6 +379,7 @@
311379 free(h);
312380 }
313381 }
382+ sp_str_lcache_clear();
314383 }
315384
316385 /* Time#strftime — format the time per `fmt` using libc