Skip to content

Instantly share code, notes, and snippets.

@xieyuschen
Created June 16, 2023 02:52
Show Gist options
  • Save xieyuschen/7d39dcf5c3271853c3d733c6ed73b661 to your computer and use it in GitHub Desktop.
Save xieyuschen/7d39dcf5c3271853c3d733c6ed73b661 to your computer and use it in GitHub Desktop.
IO.Discard vs /Dev/Null file in Golang

IO.Discard Versus Writing /Dev/Null

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
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment