Skip to content

Commit

Permalink
Avoid allocating on each call to rows.Columns (#444)
Browse files Browse the repository at this point in the history
* Cache column names for result sets

* Test that Columns() avoids allocating on second call

* Add Justin Nuß to the AUTHORS file
  • Loading branch information
nussjustin authored and julienschmidt committed May 12, 2017
1 parent aeb7d3c commit 382e13d
Show file tree
Hide file tree
Showing 3 changed files with 43 additions and 2 deletions.
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

0 comments on commit 382e13d

Please sign in to comment.