Source file src/log/slog/attr_test.go

     1  // Copyright 2022 The Go Authors. All rights reserved.
     2  // Use of this source code is governed by a BSD-style
     3  // license that can be found in the LICENSE file.
     4  
     5  package slog
     6  
     7  import (
     8  	"internal/testenv"
     9  	"testing"
    10  	"time"
    11  )
    12  
    13  func TestAttrNoAlloc(t *testing.T) {
    14  	testenv.SkipIfOptimizationOff(t)
    15  	// Assign values just to make sure the compiler doesn't optimize away the statements.
    16  	var (
    17  		i int64
    18  		u uint64
    19  		f float64
    20  		b bool
    21  		s string
    22  		x any
    23  		p = &i
    24  		d time.Duration
    25  	)
    26  	a := int(testing.AllocsPerRun(5, func() {
    27  		i = Int64("key", 1).Value.Int64()
    28  		u = Uint64("key", 1).Value.Uint64()
    29  		f = Float64("key", 1).Value.Float64()
    30  		b = Bool("key", true).Value.Bool()
    31  		s = String("key", "foo").Value.String()
    32  		d = Duration("key", d).Value.Duration()
    33  		x = Any("key", p).Value.Any()
    34  	}))
    35  	if a != 0 {
    36  		t.Errorf("got %d allocs, want zero", a)
    37  	}
    38  	_ = u
    39  	_ = f
    40  	_ = b
    41  	_ = s
    42  	_ = x
    43  }
    44  
    45  func BenchmarkAttrString(b *testing.B) {
    46  	var (
    47  		is string
    48  		u  string
    49  		f  string
    50  		bn string
    51  		s  string
    52  		x  string
    53  		ds string
    54  		p  = &is
    55  		d  time.Duration
    56  	)
    57  	b.ReportAllocs()
    58  	for i := 0; i < b.N; i++ {
    59  		is = Int64("key", 1).String()
    60  		u = Uint64("key", 1).String()
    61  		f = Float64("key", 1).String()
    62  		bn = Bool("key", true).String()
    63  		s = String("key", "foo").String()
    64  		ds = Duration("key", d).String()
    65  		x = Any("key", p).String()
    66  	}
    67  	_ = u
    68  	_ = f
    69  	_ = bn
    70  	_ = s
    71  	_ = x
    72  	_ = ds
    73  	_ = p
    74  }
    75  

View as plain text