Skip to content

Commit

Permalink
Add strings.Builder example in for's benchmark section (#838)
Browse files Browse the repository at this point in the history
* Add notes about using and benchmarking strings.Builder

* Add new version of for example

* Update roman numerals tutorial with backlink

* Fix phrasing
  • Loading branch information
domcorvasce authored Jan 22, 2025
1 parent 7c2e292 commit 23b2524
Show file tree
Hide file tree
Showing 4 changed files with 65 additions and 1 deletion.
14 changes: 14 additions & 0 deletions for/v3/repeat.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
package iteration

import "strings"

const repeatCount = 5

// Repeat returns character repeated 5 times.
func Repeat(character string) string {
var repeated strings.Builder
for i := 0; i < repeatCount; i++ {
repeated.WriteString(character)
}
return repeated.String()
}
12 changes: 12 additions & 0 deletions for/v3/repeat_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
package iteration

import "testing"

func TestRepeat(t *testing.T) {
repeated := Repeat("a")
expected := "aaaaa"

if repeated != expected {
t.Errorf("expected %q but got %q", expected, repeated)
}
}
37 changes: 37 additions & 0 deletions iteration.md
Original file line number Diff line number Diff line change
Expand Up @@ -127,6 +127,41 @@ What `136 ns/op` means is our function takes on average 136 nanoseconds to run \

**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)**.

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.

The standard library provides the `strings.Builder`[stringsBuilder] type which minimizes memory copying.
It implements a `WriteString` method which we can use to concatenate strings:

```go
const repeatCount = 5

func Repeat(character string) string {
var repeated strings.Builder
for i := 0; i < repeatCount; i++ {
repeated.WriteString(character)
}
return repeated.String()
}
```

**Note**: We have to call the `String` method to retrieve the final result.

We can use `BenchmarkRepeat` to confirm that `strings.Builder` significantly improves performance.
Run `go test -bench=. -benchmem`:

```text
goos: darwin
goarch: amd64
pkg: github.com/quii/learn-go-with-tests/for/v4
10000000 25.70 ns/op 8 B/op 1 allocs/op
PASS
```

The `-benchmem` flag reports information about memory allocations:

* `B/op`: the number of bytes allocated per iteration
* `allocs/op`: the number of memory allocations per iteration

## Practice exercises

* Change the test so a caller can specify how many times the character is repeated and then fix the code
Expand All @@ -138,3 +173,5 @@ What `136 ns/op` means is our function takes on average 136 nanoseconds to run \
* More TDD practice
* Learned `for`
* Learned how to write benchmarks

[stringsBuilder]: https://pkg.go.dev/strings#Builder
3 changes: 2 additions & 1 deletion roman-numerals.md
Original file line number Diff line number Diff line change
Expand Up @@ -208,7 +208,8 @@ func ConvertToRoman(arabic int) string {
}
```

You may not have used [`strings.Builder`](https://golang.org/pkg/strings/#Builder) before
You might remember [`strings.Builder`](https://golang.org/pkg/strings/#Builder) from our discussion
about [benchmarking](iteration.md#benchmarking)

> A Builder is used to efficiently build a string using Write methods. It minimizes memory copying.
Expand Down

0 comments on commit 23b2524

Please sign in to comment.