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

Avoid allocating on each call to rows.Columns #444

Merged
merged 3 commits into from
May 12, 2017
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions AUTHORS
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,7 @@ Jian Zhen <zhenjl at gmail.com>
Joshua Prunier <joshua.prunier at gmail.com>
Julien Lefevre <julien.lefevr at gmail.com>
Julien Schmidt <go-sql-driver at julienschmidt.com>
Justin Nuß <nuss.justin at gmail.com>
Kamil Dziedzic <kamil at klecza.pl>
Kevin Malachowski <kevin at chowski.com>
Lennart Rudolph <lrudolph at hmc.edu>
Expand Down
33 changes: 33 additions & 0 deletions driver_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -1916,3 +1916,36 @@ func TestInterruptBySignal(t *testing.T) {
}
})
}

func TestColumnsReusesSlice(t *testing.T) {
rows := mysqlRows{
rs: resultSet{
columns: []mysqlField{
{
tableName: "test",
name: "A",
},
{
tableName: "test",
name: "B",
},
},
},
}

allocs := testing.AllocsPerRun(1, func() {
cols := rows.Columns()

if len(cols) != 2 {
t.Fatalf("expected 2 columns, got %d", len(cols))
}
})

if allocs != 0 {
t.Fatalf("expected 0 allocations, got %d", int(allocs))
}

if rows.rs.columnNames == nil {
t.Fatalf("expected columnNames to be set, got nil")
}
}
11 changes: 9 additions & 2 deletions rows.go
Original file line number Diff line number Diff line change
Expand Up @@ -22,8 +22,9 @@ type mysqlField struct {
}

type resultSet struct {
columns []mysqlField
done bool
columns []mysqlField
columnNames []string
done bool
}

type mysqlRows struct {
Expand All @@ -40,6 +41,10 @@ type textRows struct {
}

func (rows *mysqlRows) Columns() []string {
if rows.rs.columnNames != nil {
return rows.rs.columnNames
}

columns := make([]string, len(rows.rs.columns))
if rows.mc != nil && rows.mc.cfg.ColumnsWithAlias {
for i := range columns {
Expand All @@ -54,6 +59,8 @@ func (rows *mysqlRows) Columns() []string {
columns[i] = rows.rs.columns[i].name
}
}

rows.rs.columnNames = columns
return columns
}

Expand Down