Skip to content

Commit

Permalink
Avoid unnessicary goroutines
Browse files Browse the repository at this point in the history
goos: linux
goarch: amd64
pkg: github.com/99designs/gqlgen/example/starwars
BenchmarkSimpleQueryNoArgs-8      300000             25093 ns/op            6453 B/op        114 allocs/op
PASS
ok      github.com/99designs/gqlgen/example/starwars    10.807s
  • Loading branch information
vektah committed Dec 8, 2018
1 parent b0ffa22 commit 5c8b1e2
Show file tree
Hide file tree
Showing 16 changed files with 687 additions and 860 deletions.
4 changes: 2 additions & 2 deletions codegen/templates/data.go

Large diffs are not rendered by default.

12 changes: 9 additions & 3 deletions codegen/templates/field.gotpl
Original file line number Diff line number Diff line change
Expand Up @@ -27,9 +27,15 @@
if !ok {
return nil
}
var out graphql.OrderedMap
out.Add(field.Alias, func() graphql.Marshaler { {{ $field.WriteJson }} }())
return &out
return graphql.WriterFunc(func(w io.Writer) {
w.Write([]byte{'{'})
graphql.MarshalString(field.Alias).MarshalGQL(w)
w.Write([]byte{':'})
func() graphql.Marshaler {
{{ $field.WriteJson }}
}().MarshalGQL(w)
w.Write([]byte{'}'})
})
}
}
{{ else }}
Expand Down
24 changes: 13 additions & 11 deletions codegen/templates/object.gotpl
Original file line number Diff line number Diff line change
Expand Up @@ -32,37 +32,39 @@ func (ec *executionContext) _{{$object.GQLType}}(ctx context.Context, sel ast.Se
})
{{end}}

{{if $object.IsConcurrent}} var wg sync.WaitGroup {{end}}
out := graphql.NewOrderedMap(len(fields))
out := graphql.NewFieldSet(fields)
invalid := false
for i, field := range fields {
out.Keys[i] = field.Alias

switch field.Name {
case "__typename":
out.Values[i] = graphql.MarshalString({{$object.GQLType|quote}})
{{- range $field := $object.Fields }}
case "{{$field.GQLName}}":
{{- if $field.IsConcurrent }}
wg.Add(1)
go func(i int, field graphql.CollectedField) {
{{- end }}
field := field
out.Concurrently(i, func() (res graphql.Marshaler) {
res = ec._{{$object.GQLType}}_{{$field.GQLName}}(ctx, field{{if not $object.Root}}, obj{{end}})
{{- if $field.ASTType.NonNull }}
if res == graphql.Null {
invalid = true
}
{{- end }}
return res
})
{{- else }}
out.Values[i] = ec._{{$object.GQLType}}_{{$field.GQLName}}(ctx, field{{if not $object.Root}}, obj{{end}})
{{- if $field.ASTType.NonNull }}
if out.Values[i] == graphql.Null {
invalid = true
}
{{- end }}
{{- if $field.IsConcurrent }}
wg.Done()
}(i, field)
{{- end }}
{{- end }}
default:
panic("unknown field " + strconv.Quote(field.Name))
}
}
{{if $object.IsConcurrent}} wg.Wait() {{end}}
out.Dispatch()
if invalid { return graphql.Null }
return out
}
Expand Down
Loading

0 comments on commit 5c8b1e2

Please sign in to comment.