Improved performances by using a bytes.Buffer pool

This commit is contained in:
Alexandre Cesaro 2015-03-14 19:03:17 +01:00
parent 6a52a50597
commit cb55422c78
2 changed files with 34 additions and 8 deletions

View File

@ -9,6 +9,7 @@ import (
"io/ioutil" "io/ioutil"
"mime" "mime"
"path/filepath" "path/filepath"
"sync"
"time" "time"
"gopkg.in/alexcesaro/quotedprintable.v1" "gopkg.in/alexcesaro/quotedprintable.v1"
@ -134,12 +135,20 @@ func (msg *Message) SetAddressHeader(field, address, name string) {
// FormatAddress formats an address and a name as a valid RFC 5322 address. // FormatAddress formats an address and a name as a valid RFC 5322 address.
func (msg *Message) FormatAddress(address, name string) string { func (msg *Message) FormatAddress(address, name string) string {
buf := getBuffer()
defer putBuffer(buf)
n := msg.encodeHeader(name) n := msg.encodeHeader(name)
if n == name { if n == name {
n = quote(name) quote(buf, name)
} else {
buf.WriteString(n)
} }
buf.WriteString(" <")
buf.WriteString(address)
buf.WriteByte('>')
return n + " <" + address + ">" return buf.String()
} }
// SetDateHeader sets a date to the given header field. // SetDateHeader sets a date to the given header field.
@ -275,8 +284,8 @@ func (msg *Message) Embed(image ...*File) {
// Stubbed out for testing. // Stubbed out for testing.
var readFile = ioutil.ReadFile var readFile = ioutil.ReadFile
func quote(text string) string { func quote(buf *bytes.Buffer, text string) {
buf := bytes.NewBufferString(`"`) buf.WriteByte('"')
for i := 0; i < len(text); i++ { for i := 0; i < len(text); i++ {
if text[i] == '\\' || text[i] == '"' { if text[i] == '\\' || text[i] == '"' {
buf.WriteByte('\\') buf.WriteByte('\\')
@ -284,6 +293,22 @@ func quote(text string) string {
buf.WriteByte(text[i]) buf.WriteByte(text[i])
} }
buf.WriteByte('"') buf.WriteByte('"')
}
return buf.String()
var bufPool = sync.Pool{
New: func() interface{} {
return new(bytes.Buffer)
},
}
func getBuffer() *bytes.Buffer {
return bufPool.Get().(*bytes.Buffer)
}
func putBuffer(buf *bytes.Buffer) {
if buf.Len() > 1024 {
return
}
buf.Reset()
bufPool.Put(buf)
} }

View File

@ -1,7 +1,6 @@
package gomail package gomail
import ( import (
"bytes"
"crypto/tls" "crypto/tls"
"errors" "errors"
"fmt" "fmt"
@ -125,7 +124,9 @@ func (m *Mailer) Send(msg *Message) error {
} }
func flattenHeader(msg *mail.Message, bcc string) []byte { func flattenHeader(msg *mail.Message, bcc string) []byte {
var buf bytes.Buffer buf := getBuffer()
defer putBuffer(buf)
for field, value := range msg.Header { for field, value := range msg.Header {
if field != "Bcc" { if field != "Bcc" {
buf.WriteString(field + ": " + strings.Join(value, ", ") + "\r\n") buf.WriteString(field + ": " + strings.Join(value, ", ") + "\r\n")