Skip to content

Commit

Permalink
Enhancement: Alternative approach to avoid reflection on load
Browse files Browse the repository at this point in the history
When loading information from the database gorp uses reflection to identify the
field that matches with the returned column name. This search can cause some
CPU/memory overhead on large systems.

An alternative approach allows the target object to bypass this logic,
forwarding the responsability of building the slice of attribute pointers to
the caller.

For example, the following type would bypass the reflection search with an extra method:

```go
type Example struct {
  FieldA string
  FieldB int
  FieldC time.Time
}

func (e *Example) DBColumns(columnNames []string) ([]interface{}, error) {
  var columns []interface{}
  for _, columnName := range columnNames {
    switch columnName {
    case "fieldA":
      columns = append(columns, e.FieldA)
    case "fieldB":
      columns = append(columns, e.FieldB)
    case "fieldC":
      columns = append(columns, e.FieldC)
    default:
      return nil, fmt.Errorf("unknown column name %q", columnName)
    }
  }
  return columns, nil
}
```

Furthermore, the application could generate these `DBColumns` methods using `go
generate`, keeping it as an automatic plugin code to speed up data loading.
  • Loading branch information
rafaeljusto committed Aug 22, 2023
1 parent 2db0f5e commit 6977e79
Show file tree
Hide file tree
Showing 2 changed files with 328 additions and 37 deletions.
Loading

0 comments on commit 6977e79

Please sign in to comment.