You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Add strings.Builder example in for's benchmark section (quii#838)
* Add notes about using and benchmarking strings.Builder
* Add new version of for example
* Update roman numerals tutorial with backlink
* Fix phrasing
Copy file name to clipboardExpand all lines: iteration.md
+37
Original file line number
Diff line number
Diff line change
@@ -127,6 +127,41 @@ What `136 ns/op` means is our function takes on average 136 nanoseconds to run \
127
127
128
128
**Note:** Sometimes, Go can optimize your benchmarks in a way that makes them inaccurate, such as eliminating the function being benchmarked. Check your benchmarks to see if the values make sense. If they seem overly optimized, you can follow the strategies in this **[blog post](https://dave.cheney.net/2013/06/30/how-to-write-benchmarks-in-go)**.
129
129
130
+
Strings in Go are immutable, meaning every concatenation, such as in our `Repeat` function, involves copying memory to accommodate the new string. This impacts performance, particularly during heavy string concatenation.
131
+
132
+
The standard library provides the `strings.Builder`[stringsBuilder] type which minimizes memory copying.
133
+
It implements a `WriteString` method which we can use to concatenate strings:
134
+
135
+
```go
136
+
const repeatCount = 5
137
+
138
+
funcRepeat(characterstring) string {
139
+
varrepeated strings.Builder
140
+
fori:=0; i < repeatCount; i++ {
141
+
repeated.WriteString(character)
142
+
}
143
+
return repeated.String()
144
+
}
145
+
```
146
+
147
+
**Note**: We have to call the `String` method to retrieve the final result.
148
+
149
+
We can use `BenchmarkRepeat` to confirm that `strings.Builder` significantly improves performance.
150
+
Run `go test -bench=. -benchmem`:
151
+
152
+
```text
153
+
goos: darwin
154
+
goarch: amd64
155
+
pkg: github.com/quii/learn-go-with-tests/for/v4
156
+
10000000 25.70 ns/op 8 B/op 1 allocs/op
157
+
PASS
158
+
```
159
+
160
+
The `-benchmem` flag reports information about memory allocations:
161
+
162
+
*`B/op`: the number of bytes allocated per iteration
163
+
*`allocs/op`: the number of memory allocations per iteration
164
+
130
165
## Practice exercises
131
166
132
167
* Change the test so a caller can specify how many times the character is repeated and then fix the code
@@ -138,3 +173,5 @@ What `136 ns/op` means is our function takes on average 136 nanoseconds to run \
0 commit comments