From 999a3ce301d3e4bec4e13dddde4b8b1358aff17e Mon Sep 17 00:00:00 2001 From: Marek Majkowski Date: Fri, 28 Feb 2014 07:03:21 -0800 Subject: [PATCH] Reduce number of memory allocations in msg.Copy Right now we allocate memory even for empty slices. This is inefficient, sticking "nil" as a slice is good enough if there are no items. --- msg.go | 33 ++++++++++++++++++++++----------- 1 file changed, 22 insertions(+), 11 deletions(-) diff --git a/msg.go b/msg.go index 03a79a82..5f2057c5 100644 --- a/msg.go +++ b/msg.go @@ -1706,20 +1706,31 @@ func (dns *Msg) Copy() *Msg { r1.MsgHdr = dns.MsgHdr r1.Compress = dns.Compress - r1.Question = make([]Question, len(dns.Question)) - copy(r1.Question, dns.Question) // TODO(miek): Question is an immutable value, ok to do a shallow-copy + if len(dns.Question) > 0 { + r1.Question = make([]Question, len(dns.Question)) + copy(r1.Question, dns.Question) // TODO(miek): Question is an immutable value, ok to do a shallow-copy + } - r1.Answer = make([]RR, len(dns.Answer)) - for i := 0; i < len(dns.Answer); i++ { - r1.Answer[i] = dns.Answer[i].copy() + if len(dns.Answer) > 0 { + r1.Answer = make([]RR, len(dns.Answer)) + for i := 0; i < len(dns.Answer); i++ { + r1.Answer[i] = dns.Answer[i].copy() + } } - r1.Ns = make([]RR, len(dns.Ns)) - for i := 0; i < len(dns.Ns); i++ { - r1.Ns[i] = dns.Ns[i].copy() + + if len(dns.Ns) > 0 { + r1.Ns = make([]RR, len(dns.Ns)) + for i := 0; i < len(dns.Ns); i++ { + r1.Ns[i] = dns.Ns[i].copy() + } } - r1.Extra = make([]RR, len(dns.Extra)) - for i := 0; i < len(dns.Extra); i++ { - r1.Extra[i] = dns.Extra[i].copy() + + if len(dns.Extra) > 0 { + r1.Extra = make([]RR, len(dns.Extra)) + for i := 0; i < len(dns.Extra); i++ { + r1.Extra[i] = dns.Extra[i].copy() + } } + return r1 }