Skip to content

Commit 6931219

Browse files
committed
use string.Builder in sankey exporter
Why this is better: Performance: strings.Builder minimizes memory allocations compared to printing line-by-line. Atomicity: fmt.Print calls are thread-safe, but if we do 10 Println calls in a loop, another goroutine could print something in between them. By building one large string and printing it once, the entire Sankey block stays together in logs.
1 parent 0304b8b commit 6931219

1 file changed

Lines changed: 11 additions & 16 deletions

File tree

exporters/sankey.go

Lines changed: 11 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -48,11 +48,14 @@ func (s *SankeyExporter) Export(tr *flowtracker.Trace) {
4848
spanNames[span.ID] = name
4949
}
5050

51-
var output []string
51+
// 2. Use strings.Builder to construct the output block
52+
var sb strings.Builder
53+
54+
if !s.CleanOutput {
55+
sb.WriteString(fmt.Sprintf("\n----- START SANKEY DATA (trace id: %s)----\n", tr.TraceID))
56+
}
5257

53-
// 2. Build the links: Parent [Duration] Child
5458
for _, span := range tr.Spans {
55-
// Skip the root node acting as a child (it has no parent)
5659
if span.ParentID == "" {
5760
continue
5861
}
@@ -61,24 +64,16 @@ func (s *SankeyExporter) Export(tr *flowtracker.Trace) {
6164
if !ok {
6265
parentName = "Unknown"
6366
}
64-
6567
currentName := spanNames[span.ID]
6668

67-
// Sankey Format: Source [Weight] Target
68-
line := fmt.Sprintf("%s [%d] %s", parentName, span.Duration, currentName)
69-
output = append(output, line)
69+
// Format: Source [Weight] Target\n
70+
sb.WriteString(fmt.Sprintf("%s [%d] %s\n", parentName, span.Duration, currentName))
7071
}
7172

72-
// 3. Print the result
7373
if !s.CleanOutput {
74-
fmt.Printf("\n----- START SANKEY DATA (trace id: %s)----\n", tr.TraceID)
74+
sb.WriteString(fmt.Sprintf("----- END SANKEY DATA (trace id: %s)----\n", tr.TraceID))
7575
}
7676

77-
for _, line := range output {
78-
fmt.Println(line)
79-
}
80-
81-
if !s.CleanOutput {
82-
fmt.Printf("----- END SANKEY DATA (trace id: %s)----\n", tr.TraceID)
83-
}
77+
// 3. Print everything in one atomic operation
78+
fmt.Print(sb.String())
8479
}

0 commit comments

Comments
 (0)