Skip to content
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 7 additions & 4 deletions dataloader.go
Original file line number Diff line number Diff line change
Expand Up @@ -227,10 +227,6 @@ func NewBatchedLoader[K comparable, V any](batchFn BatchFunc[K, V], opts ...Opti
// the registered BatchFunc.
func (l *Loader[K, V]) Load(originalContext context.Context, key K) Thunk[V] {
ctx, finish := l.tracer.TraceLoad(originalContext, key)
req := &batchRequest[K, V]{
key: key,
done: make(chan struct{}),
}

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

// Only a cache miss needs a batch request: allocating it (and its channel)
// before the cache check above wastes an allocation on every cache hit.
req := &batchRequest[K, V]{
key: key,
done: make(chan struct{}),
}

thunk := func() (V, error) {
<-req.done
result := req.result.Load()
Expand Down
Loading