types/wgkey: simplify Key.UnmarshalJSON

Instead of calling ParseHex, do the hex.Decode directly.

name             old time/op    new time/op    delta
UnmarshalJSON-8    86.9ns ± 0%    42.6ns ± 0%   -50.94%  (p=0.000 n=15+14)

name             old alloc/op   new alloc/op   delta
UnmarshalJSON-8      128B ± 0%        0B       -100.00%  (p=0.000 n=15+15)

name             old allocs/op  new allocs/op  delta
UnmarshalJSON-8      2.00 ± 0%      0.00       -100.00%  (p=0.000 n=15+15)

Signed-off-by: Josh Bleecher Snyder <josh@tailscale.com>
This commit is contained in:
Josh Bleecher Snyder 2021-04-30 15:02:31 -07:00
parent a0dacba877
commit 05bed64772
2 changed files with 18 additions and 4 deletions

View File

@ -106,11 +106,10 @@ func (k *Key) UnmarshalJSON(b []byte) error {
return errors.New("wgkey.Key: UnmarshalJSON not given a string")
}
b = b[1 : len(b)-1]
key, err := ParseHex(string(b))
if err != nil {
return fmt.Errorf("wgkey.Key: UnmarshalJSON: %v", err)
if len(b) != 2*Size {
return fmt.Errorf("wgkey.Key: UnmarshalJSON input wrong size: %d", len(b))
}
copy(k[:], key[:])
hex.Decode(k[:], b)
return nil
}

View File

@ -156,3 +156,18 @@ func BenchmarkMarshalJSON(b *testing.B) {
}
}
}
func BenchmarkUnmarshalJSON(b *testing.B) {
b.ReportAllocs()
var k Key
buf, err := k.MarshalJSON()
if err != nil {
b.Fatal(err)
}
for i := 0; i < b.N; i++ {
err := k.UnmarshalJSON(buf)
if err != nil {
b.Fatal(err)
}
}
}