Skip to content

Commit 37951d8

Browse files
committed
net/netip: optimize As4 and As16
name old time/op new time/op delta As16-8 2.88ns ± 3% 2.16ns ± 3% -25.19% (p=0.000 n=15+15) Fixes #49379 Updates #20859 Change-Id: If4cf58d19ed0e2ac0f179da5c132ed37061e4cb7 Reviewed-on: https://go-review.googlesource.com/c/go/+/361674 Trust: Josh Bleecher Snyder <[email protected]> Run-TryBot: Josh Bleecher Snyder <[email protected]> Reviewed-by: Brad Fitzpatrick <[email protected]>
1 parent 62c6ff4 commit 37951d8

File tree

2 files changed

+16
-9
lines changed

2 files changed

+16
-9
lines changed

src/net/netip/netip.go

+7-9
Original file line numberDiff line numberDiff line change
@@ -698,21 +698,19 @@ const (
698698
// IPv6 addresses with zones are returned without their zone (use the
699699
// Zone method to get it).
700700
// The ip zero value returns all zeroes.
701-
func (ip Addr) As16() [16]byte {
702-
var ret [16]byte
703-
bePutUint64(ret[:8], ip.addr.hi)
704-
bePutUint64(ret[8:], ip.addr.lo)
705-
return ret
701+
func (ip Addr) As16() (a16 [16]byte) {
702+
bePutUint64(a16[:8], ip.addr.hi)
703+
bePutUint64(a16[8:], ip.addr.lo)
704+
return a16
706705
}
707706

708707
// As4 returns an IPv4 or IPv4-in-IPv6 address in its 4-byte representation.
709708
// If ip is the zero Addr or an IPv6 address, As4 panics.
710709
// Note that 0.0.0.0 is not the zero Addr.
711-
func (ip Addr) As4() [4]byte {
710+
func (ip Addr) As4() (a4 [4]byte) {
712711
if ip.z == z4 || ip.Is4In6() {
713-
var ret [4]byte
714-
bePutUint32(ret[:], uint32(ip.addr.lo))
715-
return ret
712+
bePutUint32(a4[:], uint32(ip.addr.lo))
713+
return a4
716714
}
717715
if ip.z == z0 {
718716
panic("As4 called on IP zero value")

src/net/netip/netip_test.go

+9
Original file line numberDiff line numberDiff line change
@@ -1806,3 +1806,12 @@ func TestInvalidAddrPortString(t *testing.T) {
18061806
}
18071807
}
18081808
}
1809+
1810+
var sink16 [16]byte
1811+
1812+
func BenchmarkAs16(b *testing.B) {
1813+
addr := MustParseAddr("1::10")
1814+
for i := 0; i < b.N; i++ {
1815+
sink16 = addr.As16()
1816+
}
1817+
}

0 commit comments

Comments
 (0)