Skip to content

Commit

Permalink
optimize: Avoid allocations for printing hex
Browse files Browse the repository at this point in the history
105 ns/op
  • Loading branch information
felixge committed Jan 11, 2015
1 parent dce3bca commit 0d3ae7f
Showing 1 changed file with 3 additions and 1 deletion.
4 changes: 3 additions & 1 deletion xxd.go
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,7 @@ func XXD(r io.Reader, w io.Writer) error {

r = bufio.NewReader(r)
buf := make([]byte, 16)
hexChar := make([]byte, 2)
for {
n, err := io.ReadFull(r, buf)
if n == 0 || err == io.EOF {
Expand All @@ -49,7 +50,8 @@ func XXD(r io.Reader, w io.Writer) error {

// Hex values
for i := 0; i < n; i++ {
io.WriteString(w, hex.EncodeToString(buf[i:i+1]))
hex.Encode(hexChar, buf[i:i+1])
w.Write(hexChar)

if i%2 == 1 {
io.WriteString(w, " ")
Expand Down

0 comments on commit 0d3ae7f

Please sign in to comment.