Remove fmt.Sprintf call in attribute Render (#38) Just concatenating the strings is much faster. Before: ``` make benchmark go test -bench=. goos: darwin goarch: amd64 pkg: github.com/maragudk/gomponents BenchmarkAttr/boolean_attributes-8 8194791 139 ns/op BenchmarkAttr/name-value_attributes-8 5143292 229 ns/op PASS ok github.com/maragudk/gomponents 2.841s ``` After: ``` make benchmark go test -bench=. goos: darwin goarch: amd64 pkg: github.com/maragudk/gomponents BenchmarkAttr/boolean_attributes-8 16755404 67.0 ns/op BenchmarkAttr/name-value_attributes-8 10208625 116 ns/op PASS ok github.com/maragudk/gomponents 2.702s ```
Markus Wüstenberg markus@maragu.dk
Thu, 29 Oct 2020 15:40:14 +0100
3 files changed, 22 insertions(+), 3 deletions(-)
M gomponents.go → gomponents.go
@@ -129,9 +129,9 @@ } func (a *attr) Render() string { if a.value == nil { - return fmt.Sprintf(" %v", a.name) + return " " + a.name } - return fmt.Sprintf(` %v="%v"`, a.name, *a.value) + return " " + a.name + `="` + *a.value + `"` } func (a *attr) Place() Placement {
M gomponents_test.go → gomponents_test.go
@@ -52,6 +52,22 @@ } }) } +func BenchmarkAttr(b *testing.B) { + b.Run("boolean attributes", func(b *testing.B) { + for i := 0; i < b.N; i++ { + a := g.Attr("hat") + a.Render() + } + }) + + b.Run("name-value attributes", func(b *testing.B) { + for i := 0; i < b.N; i++ { + a := g.Attr("hat", "party") + a.Render() + } + }) +} + type outsider struct{} func (o outsider) Render() string {