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.
This commit is contained in:
Marek Majkowski 2014-02-28 07:03:21 -08:00
parent 6d77efff22
commit 999a3ce301
1 changed files with 22 additions and 11 deletions

33
msg.go
View File

@ -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
}