Skip to content

Commit b41dc14

Browse files
authored
Merge pull request #123 from Zac300/allocate-batchrequest-on-miss
Allocate batchRequest only on cache miss
2 parents b77c904 + e30f927 commit b41dc14

1 file changed

Lines changed: 7 additions & 4 deletions

File tree

dataloader.go

Lines changed: 7 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -227,10 +227,6 @@ func NewBatchedLoader[K comparable, V any](batchFn BatchFunc[K, V], opts ...Opti
227227
// the registered BatchFunc.
228228
func (l *Loader[K, V]) Load(originalContext context.Context, key K) Thunk[V] {
229229
ctx, finish := l.tracer.TraceLoad(originalContext, key)
230-
req := &batchRequest[K, V]{
231-
key: key,
232-
done: make(chan struct{}),
233-
}
234230

235231
// We need to lock both the batchLock and cacheLock because the batcher can
236232
// reset the cache when either the batchCap or the wait time is reached.
@@ -254,6 +250,13 @@ func (l *Loader[K, V]) Load(originalContext context.Context, key K) Thunk[V] {
254250
return v
255251
}
256252

253+
// Only a cache miss needs a batch request: allocating it (and its channel)
254+
// before the cache check above wastes an allocation on every cache hit.
255+
req := &batchRequest[K, V]{
256+
key: key,
257+
done: make(chan struct{}),
258+
}
259+
257260
thunk := func() (V, error) {
258261
<-req.done
259262
result := req.result.Load()

0 commit comments

Comments
 (0)