portlist: reuse bufio.Reader between files

name         old time/op    new time/op    delta
ListPorts-6    1.18ms ± 5%    1.16ms ± 5%     ~     (p=0.075 n=10+10)

name         old alloc/op   new alloc/op   delta
ListPorts-6    27.2kB ± 0%    14.9kB ± 0%  -45.14%  (p=0.001 n=8+9)

name         old allocs/op  new allocs/op  delta
ListPorts-6      90.0 ± 0%      84.0 ± 0%   -6.67%  (p=0.000 n=10+10)

Updates tailscale/corp#2566

Signed-off-by: Brad Fitzpatrick <bradfitz@tailscale.com>
This commit is contained in:
Brad Fitzpatrick 2021-09-12 21:16:03 -07:00 committed by Brad Fitzpatrick
parent 5a9d977c78
commit 61f201f33d
2 changed files with 21 additions and 8 deletions

View File

@ -40,8 +40,9 @@ func listPorts() (List, error) {
if sawProcNetPermissionErr.Get() {
return nil, nil
}
l := []Port{}
var ret []Port
var br *bufio.Reader
for _, fname := range sockfiles {
// Android 10+ doesn't allow access to this anymore.
// https://developer.android.com/about/versions/10/privacy/changes#proc-net-filesystem
@ -59,17 +60,19 @@ func listPorts() (List, error) {
if err != nil {
return nil, fmt.Errorf("%s: %s", fname, err)
}
defer f.Close()
r := bufio.NewReader(f)
ports, err := parsePorts(r, filepath.Base(fname))
if br == nil {
br = bufio.NewReader(f)
} else {
br.Reset(f)
}
ports, err := parsePorts(br, filepath.Base(fname))
f.Close()
if err != nil {
return nil, fmt.Errorf("parsing %q: %w", fname, err)
}
l = append(l, ports...)
ret = append(ret, ports...)
}
return l, nil
return ret, nil
}
// fileBase is one of "tcp", "tcp6", "udp", "udp6".

View File

@ -129,3 +129,13 @@ func BenchmarkParsePorts(b *testing.B) {
}
}
}
func BenchmarkListPorts(b *testing.B) {
b.ReportAllocs()
for i := 0; i < b.N; i++ {
_, err := listPorts()
if err != nil {
b.Fatal(err)
}
}
}