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

memory/provider.go doesn't use a pointer receiver causing the struct to be copied #586

Closed
tw1nk opened this issue Oct 11, 2021 · 2 comments

Comments

@tw1nk
Copy link

tw1nk commented Oct 11, 2021

func (d memoryDBProvider) Database(name string) (sql.Database, error) {

func (d memoryDBProvider) HasDatabase(name string) bool {

func (d memoryDBProvider) AllDatabases() []sql.Database {

func (d memoryDBProvider) CreateDatabase(ctx *sql.Context, name string) (err error) {

func (d memoryDBProvider) DropDatabase(ctx *sql.Context, name string) (err error) {

@tw1nk
Copy link
Author

tw1nk commented Oct 11, 2021

func TestProviderHasPointerReceiver(t *testing.T) {
	provider := &memoryDBProvider{}
	ref := reflect.ValueOf(provider).Elem().Type()

	for i := 0; i < ref.NumMethod(); i++ {
		method := ref.Method(i)
		if method.IsExported() {
			function := method.Func
			if function.Type().NumIn() > 0 {
				firstArg := function.Type().In(0)
				if firstArg.Kind() != reflect.Ptr {
					t.Errorf("method: memoryDBProvider.%s doesn't have a pointer receiver", method.Name)
				}
			}
		}
	}
}

tw1nk added a commit to tw1nk/go-mysql-server that referenced this issue Oct 11, 2021
@zachmu
Copy link
Member

zachmu commented Oct 12, 2021

This is intentional. The fields in memoryDbProvider are all pointer or map types themselves, so copying the struct is safe.

From a performance perspective, it's not straightforward when a pointer type outperforms a struct as a receiver. You have to benchmark the specific use case to be sure. But you're trading the higher cost of copying a struct v. a pointer with creating memory pressure via pointers. It probably doesn't matter much one way or the other here.

@zachmu zachmu closed this as completed Oct 12, 2021
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants