Skip to content

Allocate batchRequest only on cache miss#123

Merged
pavelnikolov merged 1 commit into
graph-gophers:masterfrom
Zac300:allocate-batchrequest-on-miss
May 27, 2026
Merged

Allocate batchRequest only on cache miss#123
pavelnikolov merged 1 commit into
graph-gophers:masterfrom
Zac300:allocate-batchrequest-on-miss

Conversation

@Zac300
Copy link
Copy Markdown

@Zac300 Zac300 commented May 27, 2026

Summary

Loader.Load allocated the batchRequest and its done channel at the top of the function, before the cache lookup. req is only used on a cache miss (it's sent to the batcher and read by the returned thunk), so on a cache hit it was allocated and immediately discarded — every cached load paid for a struct + channel allocation it never used.

This moves the allocation below the cache-hit early-return so cached loads don't pay for it. No behavioural change: nothing between the cache check and the new allocation site references req.

Fixes #122.

Benchmark

Load on a primed/cached key (-benchmem):

allocs/op B/op ns/op
before 3 160 45.7
after 1 16 20.5

Testing

go test . passes. (The pre-existing build failures in example/lru_cache and example/ttl_cache are unrelated to this change — they fail the same way on unmodified master.)

Loader.Load allocated the batchRequest and its done channel at the top of
the function, before the cache lookup. req is only ever used on a cache
miss (it is sent to the batcher), so on a cache hit it was allocated and
immediately discarded. Move the allocation below the cache-hit early
return so cached loads don't pay for it.

Benchmark (Load on a primed key, -benchmem):

  before: 3 allocs/op  160 B/op  45.7 ns/op
  after:  1 alloc/op    16 B/op  20.5 ns/op

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
@pavelnikolov pavelnikolov merged commit b41dc14 into graph-gophers:master May 27, 2026
1 check passed
@pavelnikolov
Copy link
Copy Markdown
Member

Released v7.2.0

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Loader.Load allocates a batchRequest + channel before the cache check

2 participants