Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

btf: Optimize string table for globally increasing offsets #1210

Merged
merged 1 commit into from
Nov 7, 2023
Merged
Show file tree
Hide file tree
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
16 changes: 15 additions & 1 deletion btf/strings.go
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ import (
type stringTable struct {
base *stringTable
offsets []uint32
prevIdx int
strings []string
}

Expand Down Expand Up @@ -61,7 +62,7 @@ func readStringTable(r sizedReader, base *stringTable) (*stringTable, error) {
return nil, errors.New("first item in string table is non-empty")
}

return &stringTable{base, offsets, strings}, nil
return &stringTable{base, offsets, 0, strings}, nil
}

func splitNull(data []byte, atEOF bool) (advance int, token []byte, err error) {
Expand All @@ -84,15 +85,28 @@ func (st *stringTable) Lookup(offset uint32) (string, error) {
}

func (st *stringTable) lookup(offset uint32) (string, error) {
// Fast path: zero offset is the empty string, looked up frequently.
if offset == 0 && st.base == nil {
return "", nil
}

// Accesses tend to be globally increasing, so check if the next string is
// the one we want. This skips the binary search in about 50% of cases.
if st.prevIdx+1 < len(st.offsets) && st.offsets[st.prevIdx+1] == offset {
st.prevIdx++
return st.strings[st.prevIdx], nil
}

i, found := slices.BinarySearch(st.offsets, offset)
if !found {
return "", fmt.Errorf("offset %d isn't start of a string", offset)
}

// Set the new increment index, but only if its greater than the current.
if i > st.prevIdx+1 {
st.prevIdx = i
}

return st.strings[i], nil
}

Expand Down
2 changes: 1 addition & 1 deletion btf/strings_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -112,5 +112,5 @@ func newStringTable(strings ...string) *stringTable {
offset += uint32(len(str)) + 1 // account for NUL
}

return &stringTable{nil, offsets, strings}
return &stringTable{nil, offsets, 0, strings}
}