From 7bed7a365754ae024e182119decf058a7ab11170 Mon Sep 17 00:00:00 2001 From: wdvxdr Date: Tue, 17 Aug 2021 17:06:00 +0800 Subject: [PATCH] jce: optimize JceWriter_WriteMap. MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit name old time/op new time/op delta JceWriter_WriteMap-8 4.09µs ± 3% 2.44µs ± 1% -40.39% (p=0.000 n=10+8) name old speed new speed delta JceWriter_WriteMap-8 22.8MB/s ± 3% 38.2MB/s ± 1% +67.73% (p=0.000 n=10+8) name old alloc/op new alloc/op delta JceWriter_WriteMap-8 2.34kB ± 0% 1.30kB ± 0% -44.37% (p=0.000 n=10+10) name old allocs/op new allocs/op delta JceWriter_WriteMap-8 52.0 ± 0% 30.0 ± 0% -42.31% (p=0.000 n=10+10) --- binary/jce/writer.go | 10 +++++----- binary/jce/writer_test.go | 16 ++++++++++++++++ 2 files changed, 21 insertions(+), 5 deletions(-) create mode 100644 binary/jce/writer_test.go diff --git a/binary/jce/writer.go b/binary/jce/writer.go index a9464e8a..702f1eb1 100644 --- a/binary/jce/writer.go +++ b/binary/jce/writer.go @@ -160,11 +160,11 @@ func (w *JceWriter) WriteMap(m interface{}, tag int) { return } w.writeHead(8, tag) - w.WriteInt32(int32(len(va.MapKeys())), 0) - for _, k := range va.MapKeys() { - v := va.MapIndex(k) - w.WriteObject(k.Interface(), 0) - w.WriteObject(v.Interface(), 1) + w.WriteInt32(int32(va.Len()), 0) + iter := va.MapRange() + for iter.Next() { + w.WriteObject(iter.Key().Interface(), 0) + w.WriteObject(iter.Value().Interface(), 1) } } diff --git a/binary/jce/writer_test.go b/binary/jce/writer_test.go new file mode 100644 index 00000000..bba1f1a8 --- /dev/null +++ b/binary/jce/writer_test.go @@ -0,0 +1,16 @@ +package jce + +import "testing" + +var globalBytes []byte + +func BenchmarkJceWriter_WriteMap(b *testing.B) { + var x = globalBytes + for i := 0; i < b.N; i++ { + w := NewJceWriter() + w.WriteMap(req.Map, 0) + x = w.Bytes() + } + globalBytes = x + b.SetBytes(int64(len(globalBytes))) +}