99designs / 99designs/gqlgen

[Question]: why generated code uses switch instead of map to store handler?

Open
#2,480 0 comments 0 reactions 0 assignees View on GitHub
Dominant language
Go
Stars
10.8k
Forks
1.3k
Avg merge
2d 36m
Merged PRs (30d)
26

Description

I found in generated code `_Query`, it uses switch to find the GraphQL functions like this:
```
func (ec *executionContext) _Query(ctx context.Context, sel ast.SelectionSet) graphql.Marshaler {
fields := graphql.CollectFields(ec.OperationContext, sel, queryImplementors)
out := graphql.NewFieldSet(fields)
for i, field := range fields {
switch field.Name {
case "__typename":
case "users":
field := field

innerFunc := func(ctx context.Context) (res graphql.Marshaler) {
// ignore recover code.
res = ec._Query_users(ctx, field)
return res
}

rrm := func(ctx context.Context) graphql.Marshaler {
return ec.OperationContext.RootResolverMiddleware(ctx, innerFunc)
}

out.Concurrently(i, func() graphql.Marshaler {
return rrm(innerCtx)
})
case "user": // also cases todos, todo, todoFromUser, __type, __schema
default:
panic("unknown field " + strconv.Quote(field.Name))
}
}
out.Dispatch()
return out
}
```
If the GraphQL functions increases in a large time, we will cost a lot of time to query, as the [go compiler doesn't optimize too much for the switch](https://groups.google.com/g/golang-nuts/c/IURR4Z2SY7M/m/R7ORD_yDix4J).

> 1. in order, all non-constant cases are
compiled and tested as if-elses.
>2. groups of larger than 3
constant cases are binary
divided and conquered.
>3. 3 or fewer cases are compared
linearly.

Do we have plan to migrate code templates from using switch to using map? Or are there some wrong points mentioned above?

Regards

Contributor guide

Open the contributing guide

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.