Created
October 16, 2024 21:03
-
-
Save adoublef/67e852a2133f429652c534082c17d554 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Copyright 2024 Rahim Afful-Brown. All Rights Reserved. | |
// | |
// Distributed under MIT license. | |
// See file LICENSE for detail or copy at https://opensource.org/licenses/MIT | |
package copy_test | |
import ( | |
"bufio" | |
"io" | |
"os" | |
"testing" | |
) | |
func Benchmark_Copy(b *testing.B) { | |
f := createFile(b) | |
b.Run("CopyBuffer", func(b *testing.B) { | |
for n := 0; n < b.N; n++ { | |
b.StopTimer() | |
f.Seek(0, io.SeekStart) | |
src := &noopReader{f} | |
dst := &noopWriter{io.Discard} | |
buf := make([]byte, 5*1024*1024) | |
b.StartTimer() | |
io.CopyBuffer(dst, src, buf) | |
} | |
}) | |
b.Run("BufioWriter", func(b *testing.B) { | |
for n := 0; n < b.N; n++ { | |
b.StopTimer() | |
f.Seek(0, io.SeekStart) | |
src := &noopReader{f} | |
dst := bufio.NewWriterSize(io.Discard, 5*1024*1024) // ReadFrom | |
b.StartTimer() | |
io.Copy(dst, src) | |
} | |
}) | |
b.Run("BufioReader", func(b *testing.B) { | |
for n := 0; n < b.N; n++ { | |
b.StopTimer() | |
f.Seek(0, io.SeekStart) | |
src := bufio.NewReaderSize(f, 5*1024*1024) // WriteTo | |
dst := &noopWriter{io.Discard} | |
b.StartTimer() | |
io.Copy(dst, src) | |
} | |
}) | |
} | |
func createFile(tb testing.TB) *os.File { | |
tb.Helper() | |
f, _ := os.CreateTemp(tb.TempDir(), "file-*.txt") | |
for i := 0; i < 20*(1024*1024); i++ { | |
f.Write([]byte("A")) | |
} | |
return f | |
} | |
type noopReader struct { | |
w io.Reader | |
} | |
func (w *noopReader) Read(b []byte) (n int, err error) { | |
return w.w.Read(b) | |
} | |
type noopWriter struct { | |
w io.Writer | |
} | |
func (w *noopWriter) Write(b []byte) (n int, err error) { | |
return w.w.Write(b) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment