From 64491466ceffcbfd66422ec2e375c35935da2e46 Mon Sep 17 00:00:00 2001 From: David Fifield Date: Sat, 24 Sep 2022 10:05:17 -0600 Subject: [PATCH] Manually unlock the mutex in ClientMap.SendQueue. Rather than use defer. It is only a tiny amount faster, but this function is frequently called. Before: $ go test -bench=BenchmarkSendQueue -benchtime=2s BenchmarkSendQueue-4 15901834 151 ns/op After: $ go test -bench=BenchmarkSendQueue -benchtime=2s BenchmarkSendQueue-4 15859948 147 ns/op https://gitlab.torproject.org/tpo/anti-censorship/pluggable-transports/snowflake/-/issues/40177 --- common/turbotunnel/clientmap.go | 5 +++-- common/turbotunnel/clientmap_test.go | 18 ++++++++++++++++++ 2 files changed, 21 insertions(+), 2 deletions(-) create mode 100644 common/turbotunnel/clientmap_test.go diff --git a/common/turbotunnel/clientmap.go b/common/turbotunnel/clientmap.go index 53d0302..2d03947 100644 --- a/common/turbotunnel/clientmap.go +++ b/common/turbotunnel/clientmap.go @@ -57,8 +57,9 @@ func NewClientMap(timeout time.Duration) *ClientMap { // necessary. func (m *ClientMap) SendQueue(addr net.Addr) chan []byte { m.lock.Lock() - defer m.lock.Unlock() - return m.inner.SendQueue(addr, time.Now()) + queue := m.inner.SendQueue(addr, time.Now()) + m.lock.Unlock() + return queue } // clientMapInner is the inner type of ClientMap, implementing heap.Interface. diff --git a/common/turbotunnel/clientmap_test.go b/common/turbotunnel/clientmap_test.go new file mode 100644 index 0000000..57d794a --- /dev/null +++ b/common/turbotunnel/clientmap_test.go @@ -0,0 +1,18 @@ +package turbotunnel + +import ( + "testing" + "time" +) + +// Benchmark the ClientMap.SendQueue function. This is mainly measuring the cost +// of the mutex operations around the call to clientMapInner.SendQueue. +func BenchmarkSendQueue(b *testing.B) { + m := NewClientMap(1 * time.Hour) + id := NewClientID() + m.SendQueue(id) // populate the entry for id + b.ResetTimer() + for i := 0; i < b.N; i++ { + m.SendQueue(id) + } +}