tl;dr

基本的にio.Writer.Write()を使用するのが高速なようです。

result

1
2
3
4
5
6
$ go test -bench . -benchmem
BenchmarkWrite-4                  	30000000	        48.7 ns/op	      16 B/op	       1 allocs/op
BenchmarkWriteWithBytes-4         	500000000	         3.95 ns/op	       0 B/op	       0 allocs/op
BenchmarkFprintf-4                	20000000	        91.5 ns/op	       0 B/op	       0 allocs/op
BenchmarkWriteTo-4                	100000000	        10.0 ns/op	       0 B/op	       0 allocs/op
BenchmarkWriteWithBufferBytes-4   	300000000	         4.31 ns/op	       0 B/op	       0 allocs/op

source

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
package main_test

import (
	"bytes"
	"fmt"
	"io"
	"net/http"
	"testing"
)

var s = "Hello, my world"
var bs = []byte(s)
var buf = bytes.Buffer{}

type NullWriter struct{}

func (w *NullWriter) Write(b []byte) (int, error) {
	return len(b), nil
}

func BenchmarkWrite(b *testing.B) {
	var w io.Writer = &NullWriter{}
	b.ResetTimer()
	for i := 0; i < b.N; i++ {
		w.Write([]byte(s))
	}
}

func BenchmarkWriteWithBytes(b *testing.B) {
	var w io.Writer = &NullWriter{}
	b.ResetTimer()
	for i := 0; i < b.N; i++ {
		w.Write(bs)
	}
}

func BenchmarkFprintf(b *testing.B) {
	var w io.Writer = &NullWriter{}
	b.ResetTimer()
	for i := 0; i < b.N; i++ {
		fmt.Fprintf(w, s)
	}
}

func BenchmarkWriteTo(b *testing.B) {
	var w io.Writer = &NullWriter{}
	b.ResetTimer()
	for i := 0; i < b.N; i++ {
		buf.WriteTo(w)
	}
}

func BenchmarkWriteWithBufferBytes(b *testing.B) {
	var w io.Writer = &NullWriter{}
	b.ResetTimer()
	for i := 0; i < b.N; i++ {
		w.Write(buf.Bytes())
	}
}