From ed00cd94f2cd01f49ee8da8b1dc0c06b66d34b2f Mon Sep 17 00:00:00 2001 From: Alberto Donizetti Date: Fri, 17 Mar 2017 18:42:58 +0100 Subject: encoding/gob: make integers encoding faster MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit name old time/op new time/op delta EncodeInt32Slice-4 14.6µs ± 2% 12.2µs ± 1% -16.65% (p=0.000 n=19+18) Change-Id: I078a171f1633ff81d7e3f981dc9a398309ecb2c0 Reviewed-on: https://go-review.googlesource.com/38269 Reviewed-by: Rob Pike --- src/encoding/gob/encode.go | 16 ++++++++-------- 1 file changed, 8 insertions(+), 8 deletions(-) (limited to 'src/encoding/gob/encode.go') diff --git a/src/encoding/gob/encode.go b/src/encoding/gob/encode.go index 50cd6adb46..d67153da90 100644 --- a/src/encoding/gob/encode.go +++ b/src/encoding/gob/encode.go @@ -8,7 +8,9 @@ package gob import ( "encoding" + "encoding/binary" "math" + "math/bits" "reflect" "sync" ) @@ -107,14 +109,12 @@ func (state *encoderState) encodeUint(x uint64) { state.b.WriteByte(uint8(x)) return } - i := uint64Size - for x > 0 { - state.buf[i] = uint8(x) - x >>= 8 - i-- - } - state.buf[i] = uint8(i - uint64Size) // = loop count, negated - state.b.Write(state.buf[i : uint64Size+1]) + + binary.BigEndian.PutUint64(state.buf[1:], x) + bc := bits.LeadingZeros64(x) >> 3 // 8 - bytelen(x) + state.buf[bc] = uint8(bc - uint64Size) // and then we subtract 8 to get -bytelen(x) + + state.b.Write(state.buf[bc : uint64Size+1]) } // encodeInt writes an encoded signed integer to state.w. -- cgit v1.3