From d653d2f4eeb5fa41e907f260bd95c205bd8e1ff7 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Felix=20Geisendo=CC=88rfer?= Date: Sun, 11 Jan 2015 17:36:51 +0100 Subject: [PATCH] optimize: avoid allocations/printf for hex offset 27.7 ns/op --- xxd.go | 10 ++++++++-- 1 file changed, 8 insertions(+), 2 deletions(-) diff --git a/xxd.go b/xxd.go index eb9cb29..402f6bb 100644 --- a/xxd.go +++ b/xxd.go @@ -6,6 +6,7 @@ import ( "fmt" "io" "os" + "strconv" ) func main() { @@ -40,11 +41,13 @@ var ( ) func XXD(r io.Reader, w io.Writer) error { - line_offset := 0 + var line_offset int64 r = bufio.NewReader(r) buf := make([]byte, 16) hexChar := make([]byte, 2) + zeroHeader := []byte("0000000: ") + hexOffset := make([]byte, 6) for { n, err := io.ReadFull(r, buf) if n == 0 || err == io.EOF { @@ -52,7 +55,10 @@ func XXD(r io.Reader, w io.Writer) error { } // Line offset - fmt.Fprintf(w, "%06x0: ", line_offset) + hexOffset = strconv.AppendInt(hexOffset[0:0], line_offset, 16) + w.Write(zeroHeader[0:(6 - len(hexOffset))]) + w.Write(hexOffset) + w.Write(zeroHeader[6:]) line_offset++ // Hex values