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 { if e.count < maxEntries {
return e.entries[:e.count] return e.entries[:e.count]
} }
res := make([]T, maxEntries) var res [maxEntries]T
copy(res, e.entries[e.index:]) if e.index >= e.count {
copy(res[maxEntries-e.index:], e.entries[:e.index]) copy(res[:], e.entries[:e.count])
return res } 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) { func (e *Entries[T]) MarshalJSON() ([]byte, error) {

View File

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