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

perf(gnovm): cache PkgIDFromPkgPath for higher performance #3424

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
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
31 changes: 31 additions & 0 deletions gnovm/pkg/gnolang/bench_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
package gnolang

import (
"testing"
)

var sink any = nil

var pkgIDPaths = []string{
"encoding/json",
"math/bits",
"github.com/gnolang/gno/gnovm/pkg/gnolang",
"a",
" ",
"",
"github.com/gnolang/gno/gnovm/pkg/gnolang/vendor/pkg/github.com/gnolang/vendored",
}

func BenchmarkPkgIDFromPkgPath(b *testing.B) {
b.ReportAllocs()
for i := 0; i < b.N; i++ {
for _, path := range pkgIDPaths {
sink = PkgIDFromPkgPath(path)
}
}

if sink == nil {
b.Fatal("Benchmark did not run!")
}
sink = nil
}
20 changes: 19 additions & 1 deletion gnovm/pkg/gnolang/realm.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import (
"fmt"
"reflect"
"strings"
"sync"

bm "github.com/gnolang/gno/gnovm/pkg/benchops"
)
Expand Down Expand Up @@ -71,8 +72,25 @@ func (pid PkgID) Bytes() []byte {
return pid.Hashlet[:]
}

var (
pkgIDMu sync.Mutex // pkgIDMu protects the shared cache.
// TODO: later on switch this to an LRU if needed to ensure
// fixed memory caps. For now though it isn't a problem:
// https://github.com/gnolang/gno/pull/3424#issuecomment-2564571785
pkgIDFromPkgPathCache = make(map[string]*PkgID, 100)
)

func PkgIDFromPkgPath(path string) PkgID {
return PkgID{HashBytes([]byte(path))}
pkgIDMu.Lock()
defer pkgIDMu.Unlock()

pkgID, ok := pkgIDFromPkgPathCache[path]
if !ok {
pkgID = new(PkgID)
*pkgID = PkgID{HashBytes([]byte(path))}
pkgIDFromPkgPathCache[path] = pkgID
}
return *pkgID
}

// Returns the ObjectID of the PackageValue associated with path.
Expand Down
Loading