8000 Avoid using `fmt.Fprintf` & `fmt.Fprint` when possible · Issue #259 · olekukonko/tablewriter · GitHub
Skip to content
Avoid using fmt.Fprintf & fmt.Fprint when possible #259
@olekukonko

Description

@olekukonko
package testing

import (
	"bytes"
	"fmt"
	"io"
	"strings"
	"sync"
	"testing"
)

func BenchmarkFprint(b *testing.B) {
	for i := 0; i < b.N; i++ {
		fmt.Fprint(io.Discard, "data")
	}
}

func BenchmarkFprintf(b *testing.B) {
	for i := 0; i < b.N; i++ {
		fmt.Fprintf(io.Discard, "data")
	}
}

func BenchmarkCopy(b *testing.B) {
	for i := 0; i < b.N; i++ {
		io.Copy(io.Discard, strings.NewReader("data"))
	}

}

func BenchmarkWrite(b *testing.B) {
	data := []byte("data")
	for i := 0; i < b.N; i++ {
		io.Discard.Write(data)
	}
}

func BenchmarkBuffer(b *testing.B) {
	buf := bytes.NewBuffer(make([]byte, 0, 32))
	for i := 0; i < b.N; i++ {
		buf.Write([]byte("data"))
		buf.Reset()
	}
}

var bufferPool = sync.Pool{
	New: func() interface{} {
		return bytes.NewBuffer(make([]byte, 0, 32))
	},
}

func BenchmarkPooledBuffer(b *testing.B) {
	for i := 0; i < b.N; i++ {
		buf := bufferPool.Get().(*bytes.Buffer)
		buf.Write([]byte("data"))
		buf.Reset()
		bufferPool.Put(buf)
	}
}
goos: darwin
goarch: arm64
pkg: github.com/olekukonko/tablewriter/tmp/testing
cpu: Apple M3 Pro
BenchmarkFprint
BenchmarkFprint-12              66543763                17.95 ns/op            0 B/op          0 allocs/op
BenchmarkFprintf
BenchmarkFprintf-12             84729055                15.33 ns/op            0 B/op          0 allocs/op
BenchmarkCopy
BenchmarkCopy-12                67571215                17.11 ns/op           32 B/op          1 allocs/op
BenchmarkWrite
BenchmarkWrite-12               1000000000               1.072 ns/op           0 B/op          0 allocs/op
BenchmarkBuffer
BenchmarkBuffer-12              443786776                2.672 ns/op           0 B/op          0 allocs/op
BenchmarkPooledBuffer
BenchmarkPooledBuffer-12        143791021                8.329 ns/op           0 B/op          0 allocs/op
PASS
ok      github.com/olekukonko/tablewriter/tmp/testing   10.043s

Metadata

Metadata

Assignees

No one assigned

    Projects

    No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions

      0