Last active
June 5, 2017 13:58
-
-
Save utahta/abc1e9c4910b4d5381d5a1b10c28be4f to your computer and use it in GitHub Desktop.
ioutil.ReadAll and base64.Encoder benchmark
This file contains 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
package bench | |
import ( | |
"bytes" | |
"encoding/base64" | |
"io" | |
"io/ioutil" | |
) | |
func read1(body io.Reader) []byte { | |
b, err := ioutil.ReadAll(body) | |
if err != nil { | |
panic(err) | |
} | |
return b | |
} | |
func read2(body io.Reader) []byte { | |
w := &bytes.Buffer{} | |
if _, err := io.Copy(w, body); err != nil { | |
panic(err) | |
} | |
return w.Bytes() | |
} | |
func encode1(body io.Reader) string { | |
w := &bytes.Buffer{} | |
if _, err := io.Copy(w, body); err != nil { | |
panic(err) | |
} | |
return base64.StdEncoding.EncodeToString(w.Bytes()) | |
} | |
func encode2(body io.Reader) string { | |
w := &bytes.Buffer{} | |
enc := base64.NewEncoder(base64.StdEncoding, w) | |
if _, err := io.Copy(enc, body); err != nil { | |
panic(err) | |
} | |
if err := enc.Close(); err != nil { | |
panic(err) | |
} | |
//b := w.Bytes() | |
//return *(*string)(unsafe.Pointer(&b)) | |
return w.String() | |
} |
This file contains 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
package bench | |
import ( | |
"bytes" | |
"io/ioutil" | |
"os" | |
"testing" | |
) | |
var image []byte | |
func init() { | |
body, _ := os.Open("/tmp/image.jpg") | |
image, _ = ioutil.ReadAll(body) | |
body.Close() | |
} | |
func TestRead(t *testing.T) { | |
r := bytes.NewReader(image) | |
a := read1(r) | |
r = bytes.NewReader(image) | |
b := read2(r) | |
if len(a) != len(b) { | |
t.Fatal("mismatch") | |
} | |
} | |
func BenchmarkRead1(b *testing.B) { | |
for i := 0; i < b.N; i++ { | |
r := bytes.NewReader(image) | |
read1(r) | |
} | |
} | |
func BenchmarkRead2(b *testing.B) { | |
for i := 0; i < b.N; i++ { | |
r := bytes.NewReader(image) | |
read2(r) | |
} | |
} | |
func TestEncode(t *testing.T) { | |
r := bytes.NewReader(image) | |
a := encode1(r) | |
r = bytes.NewReader(image) | |
b := encode2(r) | |
if a != b { | |
t.Fatalf("mismatch. a:%v b:%v", len(a), len(b)) | |
} | |
} | |
func BenchmarkEncode1(b *testing.B) { | |
for i := 0; i < b.N; i++ { | |
r := bytes.NewReader(image) | |
encode1(r) | |
} | |
} | |
func BenchmarkEncode2(b *testing.B) { | |
for i := 0; i < b.N; i++ { | |
r := bytes.NewReader(image) | |
encode2(r) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment