wgengine/filter: twiddle bits to optimize

Part of #19.

name            old time/op    new time/op    delta
Filter/icmp4-8    32.2ns ± 3%    32.5ns ± 2%     ~     (p=0.524 n=10+8)
Filter/icmp6-8    49.7ns ± 6%    43.1ns ± 4%  -13.12%  (p=0.000 n=9+10)

Signed-off-by: David Anderson <danderson@tailscale.com>
This commit is contained in:
Josh Bleecher Snyder
2020-11-12 17:10:38 -08:00
committed by David Anderson
parent 5062131aad
commit 47380ebcfb
3 changed files with 57 additions and 10 deletions
+15 -6
View File
@@ -46,8 +46,16 @@ func nets6FromIPPrefixes(pfxs []netaddr.IPPrefix) (ret []net6) {
}
func (n net6) Contains(ip packet.IP6) bool {
return ((n.ip.Hi&n.mask.Hi) == (ip.Hi&n.mask.Hi) &&
(n.ip.Lo&n.mask.Lo) == (ip.Lo&n.mask.Lo))
// This is equivalent to the more straightforward implementation:
// ((n.ip.Hi & n.mask.Hi) == (ip.Hi & n.mask.Hi) &&
// (n.ip.Lo & n.mask.Lo) == (ip.Lo & n.mask.Lo))
//
// This implementation runs significantly faster because it
// eliminates branches and minimizes the required
// bit-twiddling.
a := (n.ip.Hi ^ ip.Hi) & n.mask.Hi
b := (n.ip.Lo ^ ip.Lo) & n.mask.Lo
return (a | b) == 0
}
func (n net6) Bits() int {
@@ -128,12 +136,13 @@ func (ms matches6) match(q *packet.Parsed) bool {
}
func (ms matches6) matchIPsOnly(q *packet.Parsed) bool {
for _, m := range ms {
if !ip6InList(q.SrcIP6, m.srcs) {
for i := range ms {
if !ip6InList(q.SrcIP6, ms[i].srcs) {
continue
}
for _, dst := range m.dsts {
if dst.net.Contains(q.DstIP6) {
dsts := ms[i].dsts
for i := range dsts {
if dsts[i].net.Contains(q.DstIP6) {
return true
}
}