Commit 5daff9a1

5daff9a11a85Merged

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

Description

perf(runtime): sp_utf8_byte_offset walks without precomputing byte_len

The cache-hit path already returns O(1) for ASCII strings, but the fallback still called sp_str_byte_len before walking. For a mid-string pointer (the second sp_utf8_byte_offset call inside sp_str_sub_range, where the argument is s + boff rather than the original cached head), the cache misses and sp_str_byte_len falls through to strlen on every call. Profiling bm_json_parse showed strlen still consuming ~16% of cycles for exactly this reason.

The bl was only used as an upper bound for the walk, but the walk already stops at the requested character count. Replacing the p < end guard with *p is correctness-equivalent: sp_utf8_advance only reads p[1..cn) when the continuation-byte mask matches, and NUL never does, so a truncated multibyte sequence terminates the walk without overrunning the buffer.

Bench impact, layered on the previous commit:

  • json_parse 48 -> 41 ms (another -15%, now 7.2x vs the 296 ms pre-cache baseline)
  • huffman 8 -> 7 ms (-13%)

Geometric mean across the 28 README benchmarks: 7.52x -> 7.75x vs YJIT. Tests still pass; optcarrot still hits checksum 59662.

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

Details

Commit
5daff9a11a85
Parent
b431d9064257

lib/sp_runtime.hmodifiedView file

@@ -352,7 +352,20 @@
352352 return off > sp_str_lcache[h].byte_len ? sp_str_lcache[h].byte_len : off;
353353 }
354354 }
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);
355+ /* Walk char_idx code points or stop at the NUL terminator, whichever comes
356+ first. The loop body is safe at any *p != 0: sp_utf8_advance only reads
357+ past p[0] when the continuation-byte mask matches, and NUL doesn't match,
358+ so a truncated multibyte sequence near end-of-string still terminates. By
359+ bounding on char_idx instead of byte_len, sp_str_sub_range's second
360+ byte_offset call (on a mid-string pointer that doesn't sit in the cache)
361+ no longer pays the strlen that sp_str_byte_len would otherwise charge for
362+ a 0xff literal. */
363+ const char *p = s;
364+ while (char_idx > 0 && *p) {
365+ p += sp_utf8_advance(p);
366+ char_idx--;
367+ }
368+ return (size_t)(p - s);
356369 }
357370 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;}
358371 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;}