Skip to content

Commit 5ce4eab

Browse files
Merge pull request #7 from thatInfrastructureGuy/feature/reduceMemFootprint
Reduce sprintf call whereever possible to reduce memory allocations.
2 parents 5ef8b28 + e08375a commit 5ce4eab

File tree

1 file changed

+38
-15
lines changed

1 file changed

+38
-15
lines changed

csv.go

Lines changed: 38 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@ import (
44
"bytes"
55
"encoding/csv"
66
"fmt"
7+
"strconv"
78
"time"
89
)
910

@@ -44,27 +45,49 @@ func (c *Converter) setCSVHeaders() ([]string, int, error) {
4445

4546
func (c *Converter) stringify(values []interface{}) []string {
4647
row := make([]string, len(values), len(values))
47-
var value interface{}
4848

49-
for i := range values {
50-
rawValue := values[i]
49+
for i, rawValue := range values {
50+
if rawValue == nil {
51+
row[i] = ""
52+
continue
53+
}
5154

5255
byteArray, ok := rawValue.([]byte)
5356
if ok {
54-
value = string(byteArray)
55-
} else {
56-
value = rawValue
57+
rawValue = string(byteArray)
5758
}
5859

59-
timeValue, ok := value.(time.Time)
60-
if ok && c.TimeFormat != "" {
61-
value = timeValue.Format(c.TimeFormat)
62-
}
63-
64-
if value == nil {
65-
row[i] = ""
66-
} else {
67-
row[i] = fmt.Sprintf("%v", value)
60+
switch castValue := rawValue.(type) {
61+
case time.Time:
62+
if c.TimeFormat != "" {
63+
row[i] = castValue.Format(c.TimeFormat)
64+
}
65+
case bool:
66+
row[i] = strconv.FormatBool(castValue)
67+
case string:
68+
row[i] = castValue
69+
case int:
70+
row[i] = strconv.FormatInt(int64(castValue), 10)
71+
case int8:
72+
row[i] = strconv.FormatInt(int64(castValue), 10)
73+
case int16:
74+
row[i] = strconv.FormatInt(int64(castValue), 10)
75+
case int32:
76+
row[i] = strconv.FormatInt(int64(castValue), 10)
77+
case int64:
78+
row[i] = strconv.FormatInt(int64(castValue), 10)
79+
case uint:
80+
row[i] = strconv.FormatUint(uint64(castValue), 10)
81+
case uint8:
82+
row[i] = strconv.FormatUint(uint64(castValue), 10)
83+
case uint16:
84+
row[i] = strconv.FormatUint(uint64(castValue), 10)
85+
case uint32:
86+
row[i] = strconv.FormatUint(uint64(castValue), 10)
87+
case uint64:
88+
row[i] = strconv.FormatUint(uint64(castValue), 10)
89+
default:
90+
row[i] = fmt.Sprintf("%v", castValue)
6891
}
6992
}
7093

0 commit comments

Comments
 (0)