Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

improve: remove redundant calls of sprintf #482

Merged
merged 1 commit into from
Jun 17, 2024

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
5 checks passed
@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.

None yet

3 participants