Skip to content

Commit 82912d1

Browse files
peffgitster
authored andcommitted
strbuf_getwholeline: use getc_unlocked
strbuf_getwholeline calls getc in a tight loop. On modern libc implementations, the stdio code locks the handle for every operation, which means we are paying a significant overhead. We can get around this by locking the handle for the whole loop and using the unlocked variant. Running "git rev-parse refs/heads/does-not-exist" on a repo with an extremely large (1.6GB) packed-refs file went from: real 0m18.900s user 0m18.472s sys 0m0.448s to: real 0m10.953s user 0m10.384s sys 0m0.580s for a wall-clock speedup of 42%. All times are best-of-3, and done on a glibc 2.19 system. Note that we call into strbuf_grow while holding the lock. It's possible for that function to call other stdio functions (e.g., printing to stderr when dying due to malloc error); however, the POSIX.1-2001 definition of flockfile makes it clear that the locks are per-handle, so we are fine unless somebody else tries to read from our same handle. This doesn't ever happen in the current code, and is unlikely to be added in the future (we would have to do something exotic like add a die_routine that tried to read from stdin). Signed-off-by: Jeff King <[email protected]> Signed-off-by: Junio C Hamano <[email protected]>
1 parent f43cce2 commit 82912d1

File tree

1 file changed

+3
-1
lines changed

1 file changed

+3
-1
lines changed

strbuf.c

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -443,12 +443,14 @@ int strbuf_getwholeline(struct strbuf *sb, FILE *fp, int term)
443443
return EOF;
444444

445445
strbuf_reset(sb);
446-
while ((ch = getc(fp)) != EOF) {
446+
flockfile(fp);
447+
while ((ch = getc_unlocked(fp)) != EOF) {
447448
strbuf_grow(sb, 1);
448449
sb->buf[sb->len++] = ch;
449450
if (ch == term)
450451
break;
451452
}
453+
funlockfile(fp);
452454
if (ch == EOF && sb->len == 0)
453455
return EOF;
454456

0 commit comments

Comments
 (0)