Skip to content

Commit be67aef

Browse files
committed
preallocate batch slices
1 parent e27e905 commit be67aef

File tree

1 file changed

+24
-2
lines changed

1 file changed

+24
-2
lines changed

coderd/workspaceapps/stats.go

+24-2
Original file line numberDiff line numberDiff line change
@@ -72,7 +72,21 @@ func NewStatsDBReporter(db database.Store, batchSize int) *StatsDBReporter {
7272
// Report writes the given StatsReports to the database.
7373
func (r *StatsDBReporter) Report(ctx context.Context, stats []StatsReport) error {
7474
err := r.db.InTx(func(tx database.Store) error {
75-
var batch database.InsertWorkspaceAppStatsParams
75+
maxBatchSize := r.batchSize
76+
if len(stats) < maxBatchSize {
77+
maxBatchSize = len(stats)
78+
}
79+
batch := database.InsertWorkspaceAppStatsParams{
80+
UserID: make([]uuid.UUID, 0, maxBatchSize),
81+
WorkspaceID: make([]uuid.UUID, 0, maxBatchSize),
82+
AgentID: make([]uuid.UUID, 0, maxBatchSize),
83+
AccessMethod: make([]string, 0, maxBatchSize),
84+
SlugOrPort: make([]string, 0, maxBatchSize),
85+
SessionID: make([]uuid.UUID, 0, maxBatchSize),
86+
SessionStartedAt: make([]time.Time, 0, maxBatchSize),
87+
SessionEndedAt: make([]time.Time, 0, maxBatchSize),
88+
Requests: make([]int32, 0, maxBatchSize),
89+
}
7690
for _, stat := range stats {
7791
batch.UserID = append(batch.UserID, stat.UserID)
7892
batch.WorkspaceID = append(batch.WorkspaceID, stat.WorkspaceID)
@@ -91,7 +105,15 @@ func (r *StatsDBReporter) Report(ctx context.Context, stats []StatsReport) error
91105
}
92106

93107
// Reset batch.
94-
batch = database.InsertWorkspaceAppStatsParams{}
108+
batch.UserID = batch.UserID[:0]
109+
batch.WorkspaceID = batch.WorkspaceID[:0]
110+
batch.AgentID = batch.AgentID[:0]
111+
batch.AccessMethod = batch.AccessMethod[:0]
112+
batch.SlugOrPort = batch.SlugOrPort[:0]
113+
batch.SessionID = batch.SessionID[:0]
114+
batch.SessionStartedAt = batch.SessionStartedAt[:0]
115+
batch.SessionEndedAt = batch.SessionEndedAt[:0]
116+
batch.Requests = batch.Requests[:0]
95117
}
96118
}
97119
if len(batch.UserID) > 0 {

0 commit comments

Comments
 (0)