Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

url: reduce allocations in ParseURL #935

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
29 changes: 27 additions & 2 deletions url.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,8 +6,15 @@ import (
nurl "net/url"
"sort"
"strings"
"sync"
)

var escaperOnce sync.Once
var escaper *strings.Replacer

var parsedURLCache map[string]string
var parsedURLMu sync.Mutex

// ParseURL no longer needs to be used by clients of this library since supplying a URL as a
// connection string to sql.Open() is now supported:
//
Expand All @@ -30,6 +37,12 @@ import (
//
// This will be blank, causing driver.Open to use all of the defaults
func ParseURL(url string) (string, error) {
parsedURLMu.Lock()
cachedVal, ok := parsedURLCache[url]
parsedURLMu.Unlock()
if ok {
return cachedVal, nil
}
u, err := nurl.Parse(url)
if err != nil {
return "", err
Expand All @@ -40,7 +53,9 @@ func ParseURL(url string) (string, error) {
}

var kvs []string
escaper := strings.NewReplacer(` `, `\ `, `'`, `\'`, `\`, `\\`)
escaperOnce.Do(func() {
escaper = strings.NewReplacer(` `, `\ `, `'`, `\'`, `\`, `\\`)
})
accrue := func(k, v string) {
if v != "" {
kvs = append(kvs, k+"="+escaper.Replace(v))
Expand Down Expand Up @@ -72,5 +87,15 @@ func ParseURL(url string) (string, error) {
}

sort.Strings(kvs) // Makes testing easier (not a performance concern)
return strings.Join(kvs, " "), nil
result := strings.Join(kvs, " ")
parsedURLMu.Lock()
if parsedURLCache == nil {
parsedURLCache = make(map[string]string)
}
// don't take up an unbounded amount of memory
if len(parsedURLCache) < 100 {
parsedURLCache[url] = result
}
parsedURLMu.Unlock()
return result, nil
}