Hacking the Go compiler to efficiently map IPv4 to IPv6
The Go programming language's netip.Addr type provides an Unmap() method that extracts IPv4 addresses from IPv4-mapped IPv6 addresses. However, Go maintainers have rejected adding a Map() or To6() method to reverse the process, as they believe users should use netip.AddrFrom16(ip.As16()) instead. This pattern is currently eight times slower than a native method.
The article explores three methods to optimize this sequence: adding the reverse mapping to the standard library, implementing it as an external helper, and using the unsafe package. The standard library solution costs 0.88 ns per operation, the helper approach takes 7.14 ns, and the unsafe solution matches the performance of the first one.
The article then delves into the assembly code generated by the compiler for each solution and discusses the challenges of implementing the optimization in the Go compiler.
Written by urgent.news from Lobsters's reporting — not their text. Machine-written — may contain errors; check the original before relying on it.