refactor(metrics): optimize memory allocation in period entries

- Replace heap allocation with stack-allocated array in Entries.Get() method.
- Also refactor uptime module to use value types instead of pointer types.
This commit is contained in:
yusing
2025-10-03 23:01:09 +08:00
parent ba8edb160f
commit 1e0c7a15d8
2 changed files with 13 additions and 9 deletions

View File

@@ -58,10 +58,14 @@ func (e *Entries[T]) Get() []T {
if e.count < maxEntries {
return e.entries[:e.count]
}
res := make([]T, maxEntries)
copy(res, e.entries[e.index:])
copy(res[maxEntries-e.index:], e.entries[:e.index])
return res
var res [maxEntries]T
if e.index >= e.count {
copy(res[:], e.entries[:e.count])
} else {
copy(res[:], e.entries[e.index:])
copy(res[e.count-e.index:], e.entries[:e.index])
}
return res[:]
}
func (e *Entries[T]) MarshalJSON() ([]byte, error) {

View File

@@ -17,8 +17,8 @@ import (
type (
StatusByAlias struct {
Map map[string]*routes.HealthInfo `json:"statuses"`
Timestamp int64 `json:"timestamp"`
Map map[string]routes.HealthInfo `json:"statuses"`
Timestamp int64 `json:"timestamp"`
} // @name RouteStatusesByAlias
Status struct {
Status types.HealthStatus `json:"status" swaggertype:"string" enums:"healthy,unhealthy,unknown,napping,starting"`
@@ -42,8 +42,8 @@ type (
var Poller = period.NewPoller("uptime", getStatuses, aggregateStatuses)
func getStatuses(ctx context.Context, _ *StatusByAlias) (*StatusByAlias, error) {
return &StatusByAlias{
func getStatuses(ctx context.Context, _ StatusByAlias) (StatusByAlias, error) {
return StatusByAlias{
Map: routes.GetHealthInfo(),
Timestamp: time.Now().Unix(),
}, nil
@@ -57,7 +57,7 @@ func (s *Status) MarshalJSON() ([]byte, error) {
})
}
func aggregateStatuses(entries []*StatusByAlias, query url.Values) (int, Aggregated) {
func aggregateStatuses(entries []StatusByAlias, query url.Values) (int, Aggregated) {
limit := metricsutils.QueryInt(query, "limit", 0)
offset := metricsutils.QueryInt(query, "offset", 0)
keyword := query.Get("keyword")