Skip to content

Commit

Permalink
map: do not allocate on lookup when key doesn't exist
Browse files Browse the repository at this point in the history
Looking up a non-existing key in a map currently allocates via fmt.Errorf. Ensure that such a lookup doesn't allocate anymore.

Fixes #1516

Signed-off-by: Bryce Kahle <bryce.kahle@datadoghq.com>
  • Loading branch information
brycekahle authored Jul 23, 2024
1 parent a61222d commit 63c6cf8
Show file tree
Hide file tree
Showing 2 changed files with 18 additions and 0 deletions.
7 changes: 7 additions & 0 deletions map.go
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,10 @@ var (
ErrIterationAborted = errors.New("iteration aborted")
ErrMapIncompatible = errors.New("map spec is incompatible with existing map")
errMapNoBTFValue = errors.New("map spec does not contain a BTF Value")

// pre-allocating these errors here since they may get called in hot code paths
// and cause unnecessary memory allocations
errMapLookupKeyNotExist = fmt.Errorf("lookup: %w", sysErrKeyNotExist)
)

// MapOptions control loading a map into the kernel.
Expand Down Expand Up @@ -711,6 +715,9 @@ func (m *Map) lookup(key interface{}, valueOut sys.Pointer, flags MapLookupFlags
}

if err = sys.MapLookupElem(&attr); err != nil {
if errors.Is(err, unix.ENOENT) {
return errMapLookupKeyNotExist
}
return fmt.Errorf("lookup: %w", wrapMapError(err))
}
return nil
Expand Down
11 changes: 11 additions & 0 deletions map_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -269,6 +269,17 @@ func TestMapLookupKeyTooSmall(t *testing.T) {
qt.Assert(t, qt.IsNotNil(m.Lookup(uint32(0), &small)))
}

func TestMapLookupKeyNotFoundAllocations(t *testing.T) {
m := createArray(t)
defer m.Close()
var key, out uint32 = 3, 0

allocs := testing.AllocsPerRun(5, func() {
_ = m.Lookup(&key, &out)
})
qt.Assert(t, qt.Equals(allocs, float64(0)))
}

func TestBatchAPIMapDelete(t *testing.T) {
if err := haveBatchAPI(); err != nil {
t.Skipf("batch api not available: %v", err)
Expand Down

0 comments on commit 63c6cf8

Please sign in to comment.