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(util/gmeta): improve meta retrieving performance by adding cache for struct type #3857

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
Open
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
21 changes: 19 additions & 2 deletions util/gmeta/gmeta.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,8 @@
package gmeta

import (
"sync"

"github.com/gogf/gf/v2/container/gvar"
"github.com/gogf/gf/v2/os/gstructs"
)
Expand All @@ -20,18 +22,33 @@ const (
metaTypeName = "gmeta.Meta" // metaTypeName is for type string comparison.
)

// cachedMetadata stores the parsed metadata for struct types.
var cachedMetadata = sync.Map{}

// Data retrieves and returns all metadata from `object`.
func Data(object interface{}) map[string]string {
reflectType, err := gstructs.StructType(object)
gqcn marked this conversation as resolved.
Show resolved Hide resolved
if err != nil {
return nil
}

if cachedData, ok := cachedMetadata.Load(reflectType.Type); ok {
return cachedData.(map[string]string)
}

var metadata map[string]string
if field, ok := reflectType.FieldByName(metaAttributeName); ok {
if field.Type.String() == metaTypeName {
return gstructs.ParseTag(string(field.Tag))
metadata = gstructs.ParseTag(string(field.Tag))
}
}
return map[string]string{}

if metadata == nil {
metadata = map[string]string{}
}

cachedMetadata.Store(reflectType.Type, metadata)
return metadata
}

// Get retrieves and returns specified metadata by `key` from `object`.
Expand Down
Loading