cache: some optimizations (#2247)

Remove some optimization and lowercasing of the qname (in the end
miekg/dns should provide a fast and OK function for it).

* remove the make([]byte, 2) allocation in the key()
* use already lowercased qname in hash key calculation.

% benchcmp old.txt new.txt
benchmark                    old ns/op     new ns/op     delta
BenchmarkCacheResponse-4     9599          8735          -9.00%

Signed-off-by: Miek Gieben <miek@miek.nl>
This commit is contained in:
Miek Gieben 2018-10-29 15:13:39 +00:00 committed by Yong Tang
parent 29f4205364
commit e6d02a3fd2
2 changed files with 10 additions and 21 deletions

26
plugin/cache/cache.go vendored
View file

@ -2,7 +2,6 @@
package cache
import (
"encoding/binary"
"hash/fnv"
"net"
"time"
@ -61,10 +60,10 @@ func New() *Cache {
}
}
// Return key under which we store the item, -1 will be returned if we don't store the
// message.
// key returns key under which we store the item, -1 will be returned if we don't store the message.
// Currently we do not cache Truncated, errors zone transfers or dynamic update messages.
func key(m *dns.Msg, t response.Type, do bool) (bool, uint64) {
// qname holds the already lowercased qname.
func key(qname string, m *dns.Msg, t response.Type, do bool) (bool, uint64) {
// We don't store truncated responses.
if m.Truncated {
return false, 0
@ -74,7 +73,7 @@ func key(m *dns.Msg, t response.Type, do bool) (bool, uint64) {
return false, 0
}
return true, hash(m.Question[0].Name, m.Question[0].Qtype, do)
return true, hash(qname, m.Question[0].Qtype, do)
}
var one = []byte("1")
@ -89,18 +88,9 @@ func hash(qname string, qtype uint16, do bool) uint64 {
h.Write(zero)
}
b := make([]byte, 2)
binary.BigEndian.PutUint16(b, qtype)
h.Write(b)
for i := range qname {
c := qname[i]
if c >= 'A' && c <= 'Z' {
c += 'a' - 'A'
}
h.Write([]byte{c})
}
h.Write([]byte{byte(qtype >> 8)})
h.Write([]byte{byte(qtype)})
h.Write([]byte(qname))
return h.Sum64()
}
@ -167,7 +157,7 @@ func (w *ResponseWriter) WriteMsg(res *dns.Msg) error {
}
// key returns empty string for anything we don't want to cache.
hasKey, key := key(res, mt, do)
hasKey, key := key(w.state.Name(), res, mt, do)
msgTTL := dnsutil.MinimalTTL(res, mt)
var duration time.Duration

View file

@ -167,7 +167,7 @@ func TestCache(t *testing.T) {
state := request.Request{W: nil, Req: m}
mt, _ := response.Typify(m, utc)
valid, k := key(m, mt, state.Do())
valid, k := key(state.Name(), m, mt, state.Do())
if valid {
crr.set(m, k, mt, c.pttl)
@ -241,8 +241,7 @@ func BenchmarkCacheResponse(b *testing.B) {
for i := 0; i < b.N; i++ {
req := reqs[j]
c.ServeDNS(ctx, &test.ResponseWriter{}, req)
j++
j = j % 5
j = (j + 1) % 5
}
}