Skip to content

Commit 5748e04

Browse files
committed
connect: reduce allocations when building SET command
1 parent 128a673 commit 5748e04

File tree

1 file changed

+14
-5
lines changed

1 file changed

+14
-5
lines changed

connection.go

Lines changed: 14 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -47,7 +47,7 @@ type mysqlConn struct {
4747

4848
// Handles parameters set in DSN after the connection is established
4949
func (mc *mysqlConn) handleParams() (err error) {
50-
var params []string
50+
var cmdSet []byte
5151
for param, val := range mc.cfg.Params {
5252
switch param {
5353
// Charset: character_set_connection, character_set_client, character_set_results
@@ -64,14 +64,23 @@ func (mc *mysqlConn) handleParams() (err error) {
6464
return
6565
}
6666

67-
// Other system vars
67+
// Other system vars accumulated in a single SET command
6868
default:
69-
params = append(params, param+"="+val)
69+
if cmdSet == nil {
70+
// Heuristic: 29 chars for each other key=value to reduce reallocations
71+
cmdSet = make([]byte, 0, 4+len(param)+1+len(val)+30*(len(mc.cfg.Params)-1))
72+
cmdSet = append(cmdSet, "SET "...)
73+
} else {
74+
cmdSet = append(cmdSet, ',')
75+
}
76+
cmdSet = append(cmdSet, param...)
77+
cmdSet = append(cmdSet, '=')
78+
cmdSet = append(cmdSet, val...)
7079
}
7180
}
7281

73-
if len(params) > 0 {
74-
err = mc.exec("SET " + strings.Join(params, ","))
82+
if cmdSet != nil {
83+
err = mc.exec(string(cmdSet))
7584
if err != nil {
7685
return
7786
}

0 commit comments

Comments
 (0)