Both of them could write down nothing, however, there is still a effieciency difference. Look at the bench:
package base
import (
"io"
"os"
"testing"
)
func BenchmarkIODiscard(b *testing.B) {
discard := io.Discard
for i := 0; i < b.N; i++ {
_, _ = discard.Write([]byte("helloworld"))
}
}
func BenchmarkIODevNull(b *testing.B) {
devNull, err := os.Open(os.DevNull)
if err != nil {
panic(err)
}
for i := 0; i < b.N; i++ {
_, _ = devNull.Write([]byte("helloworld"))
}
}
func BenchmarkIOTmpFile(b *testing.B) {
devNull, err := os.Create(os.TempDir() + "bench.log")
if err != nil {
panic(err)
}
for i := 0; i < b.N; i++ {
_, _ = devNull.Write([]byte("helloworld"))
}
}
Based on the output, the IO.Discard
is much faster than /Dev/Null
file.
As no operation system call is used in IO.Discard
, it's more efficient. When it comes to write /Dev/Null
file or
a real file, that's the optimization from operation system.
goos: darwin
goarch: amd64
cpu: Intel(R) Core(TM) i7-9750H CPU @ 2.60GHz
BenchmarkIODiscard
BenchmarkIODiscard-12 55176168 18.24 ns/op
BenchmarkIODevNull
BenchmarkIODevNull-12 2449970 494.7 ns/op
BenchmarkIOTmpFile
BenchmarkIOTmpFile-12 421737 2984 ns/op
thanks for your correction, you're right.
OpenFile
is a correct version, I will update it.