@@ -67,6 +67,12 @@ private GoWriter.Writable generateContextApis() {
6767 type operationMetricsKey struct{}
6868
6969 func withOperationMetrics(parent context.Context, mp metrics.MeterProvider) (context.Context, error) {
70+ if _, ok := mp.(metrics.NopMeterProvider); ok {
71+ // not using the metrics system - setting up the metrics context is a memory-intensive operation
72+ // so we should skip it in this case
73+ return parent, nil
74+ }
75+
7076 meter := mp.Meter($S)
7177 om := &operationMetrics{}
7278
@@ -114,7 +120,10 @@ func operationMetricTimer(m metrics.Meter, name, desc string) (metrics.Float64Hi
114120 }
115121
116122 func getOperationMetrics(ctx context.Context) *operationMetrics {
117- return ctx.Value(operationMetricsKey{}).(*operationMetrics)
123+ if v := ctx.Value(operationMetricsKey{}); v != nil {
124+ return v.(*operationMetrics)
125+ }
126+ return nil
118127 }
119128 """ , scope );
120129 }
@@ -144,7 +153,12 @@ private GoWriter.Writable generateHelpers() {
144153 ctx context.Context, metric string, fn func() (T, error),
145154 opts ...metrics.RecordMetricOption,
146155 ) (T, error) {
147- instr := getOperationMetrics(ctx).histogramFor(metric)
156+ mm := getOperationMetrics(ctx)
157+ if mm == nil { // not using the metrics system
158+ return fn()
159+ }
160+
161+ instr := mm.histogramFor(metric)
148162 opts = append([]metrics.RecordMetricOption{withOperationMetadata(ctx)}, opts...)
149163
150164 start := time.Now()
@@ -157,7 +171,12 @@ ctx context.Context, metric string, fn func() (T, error),
157171 }
158172
159173 func startMetricTimer(ctx context.Context, metric string, opts ...metrics.RecordMetricOption) func() {
160- instr := getOperationMetrics(ctx).histogramFor(metric)
174+ mm := getOperationMetrics(ctx)
175+ if mm == nil { // not using the metrics system
176+ return func() {}
177+ }
178+
179+ instr := mm.histogramFor(metric)
161180 opts = append([]metrics.RecordMetricOption{withOperationMetadata(ctx)}, opts...)
162181
163182 var ended bool
0 commit comments