Commit 8433e129

8433e129a114Merged

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

Description

Read each_line into a reusable stack buffer

f.each_line { |line| ... } emitted sp_File_gets, which allocates and copies a fresh GC string for every line. In a line-oriented loop this allocation dominates: the word-count benchmark spent most of its time here. Legacy reads into a stack buffer with fgets and lets the body copy what it needs.

Add sp_File_gets_buf (fgets into a caller-provided buffer, no allocation) and emit a per-loop stack buffer for each_line. The line pointer is valid only within the iteration; this matches legacy, which assumes the line does not escape the loop body.

bm_io_wordcount: 1.34x -> 0.84x vs legacy (now faster), output matches. make test 845, make bench 57, optcarrot checksum 59662.

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

Details

Commit
8433e129a114
Parent
3f8b35a1c1d5

lib/sp_runtime.hmodifiedView file

@@ -2015,6 +2015,14 @@
20152015 memcpy(r, buf, n);
20162016 return r;
20172017 }
2018+/* Read a line into a caller-provided buffer without allocating. The returned
2019+ pointer is `buf` (or NULL at EOF); valid only until the next call. Used by
2020+ each_line loops where the line does not escape the loop body. */
2021+static inline const char *sp_File_gets_buf(sp_File *f, char *buf, int size) {
2022+ if (!f || !f->fp) return NULL;
2023+ if (!fgets(buf, size, f->fp)) return NULL;
2024+ return buf;
2025+}
20182026 static inline const char *sp_File_read(sp_File *f) {
20192027 if (!f || !f->fp) return sp_str_empty;
20202028 long pos = ftell(f->fp);