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

all: replaces []byte(fmt.Sprintf(...)) by fmt.Appendf(nil, ...) #31301

Open
wants to merge 1 commit into
base: master
Choose a base branch
from

Conversation

islishude
Copy link
Contributor

I just had a benchmark, the fmt.Appendf is a little faster and it uses less memory.

import "fmt"

func FormatByte1(n int) []byte {
	return []byte(fmt.Sprintf("key-%04d", n))
}

func FormatByte2(n int) []byte {
	return fmt.Appendf(nil, "key-%04d", n)
}

func BenchmarkFormatByte(b *testing.B) {
	const n = 1024

	b.Run("FormatByte1", func(b *testing.B) {
		for b.Loop() {
			FormatByte1(n)
		}
	})

	b.Run("FormatByte2", func(b *testing.B) {
		for b.Loop() {
			FormatByte2(n)
		}
	})
}
BenchmarkFormatByte
BenchmarkFormatByte/FormatByte1
BenchmarkFormatByte/FormatByte1-16         	17977934	        66.30 ns/op	      24 B/op	       3 allocs/op
BenchmarkFormatByte/FormatByte2
BenchmarkFormatByte/FormatByte2-16         	20140873	        59.02 ns/op	      16 B/op	       2 allocs/op
PASS
coverage: 100.0% of statements

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.

1 participant