@@ -474,6 +474,22 @@ In cases like these, it's often better to observe a cumulative value directly,
474474rather than aggregate a series of deltas in post-processing (the synchronous
475475example).
476476
477+ ### Performance Optimization for Synchronous Instruments
478+
479+ For synchronous instruments, you can use the ` Enabled ` method to check if the
480+ instrument is enabled before performing expensive operations to compute
481+ attributes or values.
482+
483+ ``` go
484+ if apiCounter.Enabled (ctx) {
485+ // compute attributes or values
486+ apiCounter.Add (ctx, 1 , metric.WithAttributes (attributes...))
487+ }
488+ ```
489+
490+ This ensures your instrumentation doesn't pay a performance penalty when no
491+ MeterProvider is configured, or when a view is configured to drop the metric.
492+
477493### Using Counters
478494
479495Counters can be used to measure a non-negative, increasing value.
@@ -497,7 +513,9 @@ func init() {
497513 panic (err)
498514 }
499515 http.HandleFunc (" /" , func (w http.ResponseWriter , r *http.Request ) {
500- apiCounter.Add (r.Context (), 1 )
516+ if apiCounter.Enabled (r.Context ()) {
517+ apiCounter.Add (r.Context (), 1 )
518+ }
501519
502520 // do some work in an API call
503521 })
@@ -535,13 +553,19 @@ func init() {
535553func addItem () {
536554 // code that adds an item to the collection
537555
538- itemsCounter.Add (context.Background (), 1 )
556+ ctx := context.Background ()
557+ if itemsCounter.Enabled (ctx) {
558+ itemsCounter.Add (ctx, 1 )
559+ }
539560}
540561
541562func removeItem () {
542563 // code that removes an item from the collection
543564
544- itemsCounter.Add (context.Background (), -1 )
565+ ctx := context.Background ()
566+ if itemsCounter.Enabled (ctx) {
567+ itemsCounter.Add (ctx, -1 )
568+ }
545569}
546570```
547571
@@ -597,7 +621,9 @@ func init() {
597621func recordFanSpeed () {
598622 ctx := context.Background ()
599623 for fanSpeed := range fanSpeedSubscription {
600- speedGauge.Record (ctx, fanSpeed)
624+ if speedGauge.Enabled (ctx) {
625+ speedGauge.Record (ctx, fanSpeed)
626+ }
601627 }
602628}
603629```
@@ -632,7 +658,9 @@ func init() {
632658 // do some work in an API call
633659
634660 duration := time.Since (start)
635- histogram.Record (r.Context (), duration.Seconds ())
661+ if histogram.Enabled (r.Context ()) {
662+ histogram.Record (r.Context (), duration.Seconds ())
663+ }
636664 })
637665}
638666```
0 commit comments