Skip to content

Comments

improve: remove redundant calls of sprintf#482

Merged
boyter merged 1 commit intoboyter:masterfrom
apocelipes:remove-redundant-sprintf
Jun 17, 2024
Merged

improve: remove redundant calls of sprintf#482
boyter merged 1 commit intoboyter:masterfrom
apocelipes:remove-redundant-sprintf

Conversation

@apocelipes
Copy link
Contributor

  • replace fmt.Println(fmt.Sprintf(...)) with fmt.Printf, this is simpler.
  • replace sb.WriteString(fmt.Sprintf(...)) with fmt.Fprintf, this is simpler and much faster:
$ benchstat old.bench new.bench
goos: windows
goarch: amd64
pkg: testbuilder
cpu: Intel(R) Core(TM) i5-10200H CPU @ 2.40GHz
          │  old.bench  │              new.bench              │
          │   sec/op    │   sec/op     vs base                │
Builder-8   1.808µ ± 2%   1.533µ ± 1%  -15.19% (p=0.000 n=10)

          │  old.bench   │              new.bench               │
          │     B/op     │     B/op      vs base                │
Builder-8   1.281Ki ± 0%   1.000Ki ± 0%  -21.95% (p=0.000 n=10)

          │  old.bench  │             new.bench              │
          │  allocs/op  │ allocs/op   vs base                │
Builder-8   15.000 ± 0%   6.000 ± 0%  -60.00% (p=0.000 n=10)

Benchmark code is here:

// the old one
func BenchmarkBuilder(b *testing.B) {
	for range b.N {
		var sb strings.Builder
		for i := range 10 {
			sb.WriteString(fmt.Sprintf("%d. writing an integer number: %d", i, i))
		}
	}
}

// the new one
func BenchmarkBuilder(b *testing.B) {
	for range b.N {
		sb := &strings.Builder{}
		for i := range 10 {
			fmt.Fprintf(sb, "%d. writing an integer number: %d", i, i)
		}
	}
}

Copy link
Contributor

@ccoVeille ccoVeille left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

LGTM 👍 thanks

@boyter boyter merged commit ec1b7f5 into boyter:master Jun 17, 2024
@apocelipes apocelipes deleted the remove-redundant-sprintf branch June 17, 2024 08:48
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants