Use strings.Builder instead of += concatenation in loops

This commit is contained in:
Yasuhiro Matsumoto
2026-02-20 16:06:33 +09:00
parent e599573ed4
commit bca92433ba
3 changed files with 58 additions and 63 deletions
+26 -35
View File
@@ -10,6 +10,7 @@ import (
"fmt"
"os"
"path/filepath"
"strings"
"time"
)
@@ -100,7 +101,8 @@ func (ms *MemoryStore) AppendToday(content string) error {
// GetRecentDailyNotes returns daily notes from the last N days.
// Contents are joined with "---" separator.
func (ms *MemoryStore) GetRecentDailyNotes(days int) string {
var notes []string
var sb strings.Builder
first := true
for i := 0; i < days; i++ {
date := time.Now().AddDate(0, 0, -i)
@@ -109,53 +111,42 @@ func (ms *MemoryStore) GetRecentDailyNotes(days int) string {
filePath := filepath.Join(ms.memoryDir, monthDir, dateStr+".md")
if data, err := os.ReadFile(filePath); err == nil {
notes = append(notes, string(data))
if !first {
sb.WriteString("\n\n---\n\n")
}
sb.Write(data)
first = false
}
}
if len(notes) == 0 {
return ""
}
// Join with separator
var result string
for i, note := range notes {
if i > 0 {
result += "\n\n---\n\n"
}
result += note
}
return result
return sb.String()
}
// GetMemoryContext returns formatted memory context for the agent prompt.
// Includes long-term memory and recent daily notes.
func (ms *MemoryStore) GetMemoryContext() string {
var parts []string
// Long-term memory
longTerm := ms.ReadLongTerm()
if longTerm != "" {
parts = append(parts, "## Long-term Memory\n\n"+longTerm)
}
// Recent daily notes (last 3 days)
recentNotes := ms.GetRecentDailyNotes(3)
if recentNotes != "" {
parts = append(parts, "## Recent Daily Notes\n\n"+recentNotes)
}
if len(parts) == 0 {
if longTerm == "" && recentNotes == "" {
return ""
}
// Join parts with separator
var result string
for i, part := range parts {
if i > 0 {
result += "\n\n---\n\n"
}
result += part
var sb strings.Builder
sb.WriteString("# Memory\n\n")
if longTerm != "" {
sb.WriteString("## Long-term Memory\n\n")
sb.WriteString(longTerm)
}
return fmt.Sprintf("# Memory\n\n%s", result)
if recentNotes != "" {
if longTerm != "" {
sb.WriteString("\n\n---\n\n")
}
sb.WriteString("## Recent Daily Notes\n\n")
sb.WriteString(recentNotes)
}
return sb.String()
}