Reflection and unsafe
reflect and unsafe remove compile-time checks. Libraries use them, so you must read them, and normal code rarely needs them. Here are the rules, recorded from real runs, and the measured cost of each.
- 1reflect sees what an interface holds. To change a value, pass a pointer and call Elem.
- 2Reflect at setup and store the result. encoding/json walks a type once and reuses a function for every later call.
- 3unsafe.String shares memory. If the bytes change, the string changes, also inside a map.
- 4Use generics when you know the shape at compile time. Use reflect only for types you cannot name, and unsafe only with a profile.
package main
import (
"fmt"
"unsafe"
)
func main() {
m := map[string]int{}
b := []byte("alice")
key := unsafe.String(&b[0], len(b))1 // no copy
m[key] = 1
b[0] = 'z'2 // reuse the buffer for the next record
fmt.Println(len(m))
fmt.Println(m["alice"], m["zlice"]3)
for k, v := range m {
fmt.Println(k, v)
}
}- 1The string points at the bytes of b. No copy happens.
- 2Changes the string too, because a string header points at the same memory.
- 3The map hashed "alice", and the key now reads "zlice". The entry sits where neither lookup goes.
1
0 0
zlice 11
1 0
alice 1- The map holds 1 entry, and no lookup can reach it.
- The race detector and go vet report nothing here. One goroutine does all of this.
- The fix is the copy. Panel I shows that the compiler often removes it for you.
unsafe.String shares the bytes. If the buffer changes after the string goes into a map, the key cannot be found by any lookup.
- A call to ValueOf converts its argument to an interface, so the Value starts from a copy.
- A pointer is copied too, but it still leads to the original. Elem follows it.
An interface holds a type word and a data word. TypeOf reads the first. ValueOf keeps both, and a flag says if the data can change.
| ask | call |
|---|---|
| What is it called? | TypeOf(x) |
| What shape is it? | t.Kind() |
| What does it hold? | ValueOf(x) |
| What is behind it? | v.Elem() |
| Can I change it? | v.CanSet() |
| Back to a Go value | v.Interface() |
Switch on Kind, not on Type. There are 26 kinds and no limit on named types.
Type says what it is called, Kind says what shape it has, and Value holds the data.
| what you hold | code | CanAddr | CanSet | what Set did |
|---|---|---|---|---|
| A plain variable | ValueOf(x) | false | false | using unaddressable value |
| The pointer itself | ValueOf(&x) | false | false | using unaddressable value |
| Through the pointer | ValueOf(&x).Elem() | true | true | wrote the original |
| Field of a struct copy | ValueOf(s).Field(0) | false | false | using unaddressable value |
| Field through a pointer | ValueOf(&s).Elem().Field(0) | true | true | wrote the original |
| Unexported field through a pointer | ValueOf(&s).Elem().Field(1) | true | false | using value obtained using unexported field |
| Element of an array copy | ValueOf(arr).Index(0) | false | false | using unaddressable value |
| Element of a slice | ValueOf(slice).Index(0) | true | true | wrote the original |
| Map value | ValueOf(m).MapIndex(ValueOf("a")) | false | false | using unaddressable value |
A slice header holds a pointer, so its elements are addressable even when the header is a copy. A map value is never addressable: a map can move its entries.
A Value is settable if it is addressable and I reached it through exported names. A copy never is. A slice element is, because the header points at the array.
// Field is one exported field of a struct.
type Field struct {
Name, Type, Kind, Tag string
}
// Describe lists the exported fields of a struct or a struct pointer.
func Describe(v any) ([]Field, error) {
t := reflect.TypeOf(v)
if t == nil1 {
return nil, errors.New("describe: nil has no type")
}
if t.Kind() == reflect.Pointer2 {
t = t.Elem()
}
if t.Kind() != reflect.Struct {
return nil, fmt.Errorf("describe: %s is not a struct", t)
}
var out []Field
for f := range t.Fields()3 {
if !f.IsExported() {
continue
}
out = append(out, Field{
Name: f.Name,
Type: f.Type.String(),
Kind: f.Type.Kind().String(),
Tag: f.Tag.Get("json")4,
})
}
return out, nil
}- 1A nil interface has no type word. Each method call on this nil would panic.
- 2Accept both forms. Elem on a type gives the type it points to.
- 3An iterator: Go 1.26. Older code loops to NumField and calls Field(i).
- 4A tag is a plain string. Get parses it on each call, so store the result.
I check for nil, follow one pointer, confirm the kind is struct, and range over the fields. Each check replaces a panic.
// Fill sets each field of the struct at dst that has an env tag.
// lookup returns the text for a tag, or false when there is none.
func Fill(dst any, lookup func(string) (string, bool)) error {
p := reflect.ValueOf(dst)
if p.Kind() != reflect.Pointer || p.IsNil()1 {
return fmt.Errorf("fill: need a non-nil pointer, got %T", dst)
}
v := p.Elem()
if v.Kind() != reflect.Struct {
return fmt.Errorf("fill: %s is not a struct", v.Type())
}
for f, fv := range v.Fields()2 {
key, ok := f.Tag.Lookup("env")3
if !ok {
continue
}
if !fv.CanSet()4 {
return fmt.Errorf("fill: %s is not exported", f.Name)
}
text, ok := lookup(key)
if !ok {
continue
}
switch fv.Kind()5 {
case reflect.String:
fv.SetString(text)
case reflect.Int, reflect.Int64:
n, err := strconv.ParseInt(text, 10, 64)
if err != nil {
return fmt.Errorf("fill: %s: %w", key, err)
}
fv.SetInt(n)
case reflect.Bool:
b, err := strconv.ParseBool(text)
if err != nil {
return fmt.Errorf("fill: %s: %w", key, err)
}
fv.SetBool(b)
default:
return fmt.Errorf("fill: %s: no rule for %s", key, fv.Kind())
}
}
return nil
}- 1A struct passed by value gives a copy. Return an error here, not a panic later.
- 2Yields the StructField and the field Value together: Go 1.26.
- 3Lookup separates a missing tag from an empty one. Get cannot.
- 4A tagged unexported field would panic on Set.
- 5One case per kind, so a named type such as type Port int works too.
A tag-driven loader needs a pointer, a CanSet check and a switch on Kind. Every mistake appears at run time, so tests must cover it.
- Since Go 1.27, encoding/json runs on the v2 implementation. The cache is a sync.Map from reflect.Type to a pair of functions.
- The first call for a type pays for the walk. If two goroutines race on it, both build and one result stays.
- Marshal needs an addressable value, so it copies a non-pointer into new memory first. Pass a pointer and that copy goes away (panel I).
- The walk skips unexported fields. Reflect refuses to set them, so a decode could not fill them.
encoding/json reflects once per type and stores a function. After the first call, it follows the plan and does not read tags again.
// step writes one field. Each struct type gets one list of steps.
type step struct {
index int // field position, for v.Field
key []byte
write func(buf []byte, v reflect.Value) []byte
}
// plans maps a reflect.Type to its []step.
var plans sync.Map1
func planFor(t reflect.Type) ([]step, error) {
if p, ok := plans.Load(t)2; ok {
return p.([]step), nil
}
p, err := buildPlan(t)
if err != nil {
return nil, err
}
stored, _ := plans.LoadOrStore(t, p)3
return stored.([]step), nil
}
// buildPlan does the slow work once per type: it reads every field and
// tag, and picks a writer by Kind.
func buildPlan(t reflect.Type) ([]step, error) {
var steps []step
for f := range t.Fields() {
name, ok := f.Tag.Lookup("json")4
if !f.IsExported() || name == "-" {
continue
}
if !ok {
name = f.Name
}
s := step{index: f.Index[0]}
s.key = strconv.AppendQuote(nil, name)
s.key = append(s.key, ':')
switch f.Type.Kind()5 {
case reflect.String:
s.write = func(b []byte, v reflect.Value) []byte {
return strconv.AppendQuote(b, v.String())
}
case reflect.Int, reflect.Int64:
s.write = func(b []byte, v reflect.Value) []byte {
return strconv.AppendInt(b, v.Int(), 10)
}
case reflect.Bool:
s.write = func(b []byte, v reflect.Value) []byte {
return strconv.AppendBool(b, v.Bool())
}
default:
return nil, fmt.Errorf("plan: %s: no writer", f.Type)
}
steps = append(steps, s)
}
return steps, nil
}
// Encode writes a struct as a JSON object. The plan lookup is one map
// read, so only the first call for a type pays for the field walk.
func Encode(x any) ([]byte, error) {
v := reflect.ValueOf(x)
if v.Kind() != reflect.Struct {
return nil, fmt.Errorf("encode: %T is not a struct", x)
}
steps, err := planFor(v.Type())
if err != nil {
return nil, err
}
return run(steps, v), nil
}
func run(steps []step, v reflect.Value) []byte {
buf := make([]byte, 0, 128)
buf = append(buf, '{')
for i, s := range steps {
if i > 0 {
buf = append(buf, ',')
}
buf = append(buf, s.key...)
buf = s.write(buf, v.Field(s.index)6)
}
return append(buf, '}')
}- 1reflect.Type is comparable, so it works as a map key. Types are few and live forever, so the map cannot grow without limit.
- 2The common path: one read with no lock.
- 3Two goroutines can build a plan at once. Both use the one that was stored.
- 4Tags are read here, once per type, and never on the request path.
- 5The Kind switch runs once. Later calls go straight to the closure.
- 6An index is what remains of the field name. FieldByName would scan the fields on each call.
I can write this shape in an interview: one sync.Map keyed on the type, one slice of steps, and one closure per field.
| operation | plain Go | with reflect | factor | allocations |
|---|---|---|---|---|
| Read a field by index | 1.0 ns | 3.4 ns | 3× | 0 and 0 |
| Read a field by name | 1.0 ns | 46.7 ns | 45× | 0 and 0 |
| Write a field | 1.2 ns | 3.4 ns | 3× | 0 and 0 |
| Call a function | 1.1 ns | 199 ns | 174× | 0 and 2 |
| Search 100 ints | 38.5 ns | 4,391 ns | 114× | 0 and 101 |
| encode one struct, 4 fields | time | allocations |
|---|---|---|
| By hand, no reflection | 121 ns | 1 |
| Small encoder, stored plan | 227 ns | 2 |
| Small encoder, plan rebuilt on each call | 1,143 ns | 18 |
| json.Marshal(&v) | 311 ns | 1 |
| json.Marshal(v) | 428 ns | 3 |
| bytes to string | time | allocations | status |
|---|---|---|---|
| string(b), 32 bytes | 19.4 ns | 1 | Copy |
| unsafe.String, 32 bytes | 1.4 ns | 0 | Shared memory |
| m[string(b)] | 11.6 ns | 0 | Compiler skips the copy |
| m[unsafe view] | 11.5 ns | 0 | No gain |
- Rebuilding the plan on each call costs 5 times the stored plan. That is the gain from the cache in panel H.
- The compiler already avoids the copy in m[string(b)], in comparisons, and in concatenation. Check before you add unsafe.
- json.Marshal does more than the small encoder: escaping, nested types, marshaler methods. The two are not direct rivals.
Reflect costs about 3 times on a field and about 174 times on a call. Interface conversions allocate, so the Contains loop costs about 114 times.
// ContainsAny is the shape from before generics. Each mistake waits for
// run time, and each element costs an interface conversion.
func ContainsAny(list, x any) bool1 {
v := reflect.ValueOf(list)
for i := range v.Len() { // panics if list is not a slice
if reflect.DeepEqual(v.Index(i).Interface()2, x) {
return true
}
}
return false
}
// Contains is the same function with a type parameter. The compiler
// checks the element type and comparability at each call.
func Contains[T comparable]3(list []T, x T) bool {
for _, v := range list {
if v == x {
return true
}
}
return false
}- 1Accepts anything. ContainsAny([]int{2}, int64(2)) compiles and returns false.
- 2One allocation per element, because each int must go into an interface.
- 3A wrong call is a compile error. The standard form is slices.Contains.
If I can write the shape as a type parameter, the compiler checks it and the loop allocates nothing.
| before | now | since |
|---|---|---|
| sort.Slice | slices.SortFunc | 1.21 |
| reflect.DeepEqual on slices | slices.Equal | 1.21 |
| v.MapKeys() | maps.Keys | 1.23 |
| atomic.Value | atomic.Pointer[T] | 1.19 |
| TypeOf((*T)(nil)).Elem() | TypeFor[T]() | 1.22 |
| v.Interface().(T) | reflect.TypeAssert[T](v) | 1.25 |
Still reflection: encoders, field walks, tags, fmt, and anything that meets a type at run time.
Generics replaced reflection over shapes. Reflection over field names stays, because no type parameter can list a struct's fields.
| pattern | form | condition | status |
|---|---|---|---|
| 1. Reinterpret a value | (*T2)(unsafe.Pointer(p)) | T2 is no larger than T1, and the layouts match. | Layouts match |
| 2. Print an address | uintptr(unsafe.Pointer(p)) | The integer never goes back to a pointer. | Approved |
| 3. Pointer arithmetic | unsafe.Add(p, n) | The result stays inside the same allocation. One past the end is invalid. | Same allocation |
| 4. System call argument | syscall.Syscall(n, uintptr(unsafe.Pointer(p)), ...) | The conversion sits in the call expression itself. | In the call |
| 5. reflect result | unsafe.Pointer(v.Pointer()) | Convert in the same expression. Prefer v.UnsafePointer. | Same expression |
| 6. Header Data field | hdr.Data | Deprecated since Go 1.21. Use the functions in panel M. | Deprecated |
| Store a uintptr, convert later | u := uintptr(p); unsafe.Pointer(u + 8) | The object can move or die between the two lines. | Not approved |
| Point one past the end | unsafe.Add(p, unsafe.Sizeof(s)) | Unlike C, Go treats this as invalid. | Not approved |
There are six valid patterns. A uintptr is a number and not a reference, so the garbage collector ignores it. Convert back in one expression.
// BytesView returns b as a string with no copy. The caller must not
// change b while the string is in use.
func BytesView(b []byte) string {
return unsafe.String(unsafe.SliceData(b), len(b))1
}
// StringView returns s as a byte slice with no copy. The caller must
// never write to the result: string memory can be read-only.
func StringView(s string) []byte {
return unsafe.Slice(unsafe.StringData(s), len(s))2
}
// Float64Bits reads the bits of f as a uint64. Both types have the same
// size, so this is valid pattern 1. Prefer math.Float64bits.
func Float64Bits(f float64) uint64 {
return *(*uint64)(unsafe.Pointer(&f))3
}
// Second reads the element after p in an array. The result must stay
// inside the same allocation.
func Second(p *[2]int64) int64 {
return *(*int64)(unsafe.Add(unsafe.Pointer(p), unsafe.Sizeof(p[0]))4)
}- 1Go 1.20. The contract: b does not change while the string lives. Nothing checks it.
- 2A write to this slice can crash, because string data may sit in read-only memory.
- 3Pattern 1, and the body of math.Float64bits.
- 4Pattern 3. unsafe.Add arrived in Go 1.17 and keeps the pointer type all the way.
These four functions build and take apart slices and strings with no knowledge of the header layout. I document who owns the memory.
| mistake | plain build | with -race |
|---|---|---|
| Convert *int64 to a pointer to a larger struct | Runs | converted pointer straddles multiple allocations |
| Convert a byte address to a pointer type at an odd address | Runs | misaligned pointer conversion |
| unsafe.Add moves out of the allocation | Runs | pointer arithmetic result points to invalid allocation |
- go vet reports a stored uintptr: possible misuse of unsafe.Pointer.
- Nothing reports the trap in panel A. The memory stays valid, and only the meaning changes.
- The check is best effort. The runtime source names a gap: a range that covers an allocation with neither end inside it.
go test -race turns on checkptr, which checks each unsafe conversion at run time. A clean run proves nothing about the paths it did not take.
package main
import (
"fmt"
"unsafe"
)
type Loose struct {
OK bool
ID int64
Kind uint8
N int32
Code int16
}
type Tight struct {
ID int64
N int32
Code int16
OK bool
Kind uint8
}
func main() {
var l Loose
var t Tight
fmt.Println(unsafe.Sizeof(l)1, unsafe.Alignof(l)2)
fmt.Println(unsafe.Offsetof(l.ID)3, unsafe.Offsetof(l.N))
fmt.Println(unsafe.Sizeof(t), unsafe.Alignof(t))
fmt.Println(unsafe.Offsetof(t.N), unsafe.Offsetof(t.Kind))
}- 1A compile-time constant. It counts the struct and never follows a pointer.
- 2The largest alignment of any field: 8, from int64.
- 3OK takes byte 0, so ID must skip to byte 8.
32 8
8 20
16 8
8 15| rule | status |
|---|---|
| Reorder a struct held by the million, after a profile | Approved |
| Keep fields in reading order everywhere else | Approved |
| Mark a struct passed to host APIs with structs.HostLayout | Approved |
| Reorder every struct by habit | Readers pay |
| Assume the layout of a struct from another package | Not approved |
Today the compiler keeps declared order. The spec does not promise that, so host APIs need the marker. Sizes are for 64-bit systems.
Each field sits at a multiple of its alignment, and the size rounds up to the largest alignment. Sort large to small and the gaps go.
32 bytes
16 bytes of data, 16 of padding.
1 million elements: 32 MB in a slice.
The 120 orders range from 16 to 32 bytes.
- field
- padding
- not used by this order
- Press a field to move it one place to the left. Each state is a real type that the runtime built.
- The size matches unsafe.Sizeof on the compiled Tight and Loose structs. A test asserts this.
The same five fields take from 16 to 32 bytes. In a slice of 1 million, that is 16 MB for nothing.
| situation | use | status |
|---|---|---|
| Encode, decode or print a type you cannot name | reflect, or a library built on it | Approved |
| Read struct tags at startup, once | reflect | Approved |
| Compare in a test | reflect.DeepEqual | Approved |
| The same function for several element types | A type parameter | Approved |
| A few known behaviours | An interface or a type switch | Approved |
| A wire format on a hot path | Generated code, with no reflection at run time | Approved |
| Zero-copy parse where a profile shows the copy, and the input stays fixed | unsafe.String | With a profile |
| Business rules that dispatch on a field name | reflect | Not approved |
| Reach an unexported field of another package | unsafe | Breaks on upgrade |
| Avoid an allocation that no profile shows | unsafe | Not approved |
I use reflect inside libraries and at startup. I use unsafe only with a profile, a test, and a comment that names the memory owner.
| since | what changed | what it means here |
|---|---|---|
| 1.17 | unsafe.Add and unsafe.Slice. | Arithmetic and slicing with no uintptr in your code. |
| 1.18 | Generics. reflect.Pointer and PointerTo as new names. Value.UnsafePointer. | Most reflection over shapes can go. |
| 1.20 | unsafe.String, StringData and SliceData. Value.SetZero, Grow, Comparable and Equal. | Build a string or a slice with no header types. |
| 1.21 | ValueOf no longer forces its argument to the heap. Value.Clear. SliceHeader and StringHeader deprecated. | Field reads through reflect can stay allocation-free. |
| 1.22 | reflect.TypeFor. PtrTo deprecated. Value.IsZero matches the == operator on negative zero. | TypeFor names an interface type with no pointer trick. |
| 1.23 | Value.Seq and Seq2, Type.CanSeq, reflect.SliceAt. structs.HostLayout. | Range over any rangeable Value. |
| 1.24 | The omitzero JSON tag option. | Drops a zero time.Time, which omitempty keeps. |
| 1.25 | reflect.TypeAssert. encoding/json/v2 as an experiment. | Get a typed value out of a Value with no extra allocation. |
| 1.26 | Type.Fields, Methods, Ins and Outs iterators. Value.Fields and Methods. | The loops in panels E and F. |
| 1.27 | encoding/json/v2 and jsontext ship, and encoding/json runs on v2. Generic methods. The go fix unsafefuncs modernizer. | Behaviour stays, but error text can differ. GOEXPERIMENT=nojsonv2 restores the old code for now. Reflect does not list generic methods. |
| when | the moment | what to do or say |
|---|---|---|
| build | A JSON field comes back empty. | Check that the field is exported. Reflect cannot set a lowercase field, and json skips it with no error. |
| build | A decode changes nothing. | Pass a pointer. A struct value gives json a copy that it cannot set, so it returns an error. |
| build | Two endpoints repeat a decode and validate step. | Write one generic helper. Do not write a reflective validator in 45 minutes. |
| build | A test compares two structs. | Use reflect.DeepEqual, or == if every field is comparable. |
| talk | "How does json know the fields?" | Panel G: one walk per type, a stored function, and a sync.Map keyed on the type. |
| talk | "This endpoint spends 30% in JSON. What now?" | Pass pointers, reuse buffers, then consider generated code. Name unsafe last and say why. |
| talk | "Could you avoid this allocation with unsafe?" | Yes, if a profile shows it and the bytes never change. Then show the trap from panel A. |
| talk | "How much does field order save?" | Nothing for one struct. For millions of elements, multiply the size difference by the count. |
I keep reflection inside encoding/json. In my own code, types and interfaces do the work.
0 of 12 known
Predict the output.
package main import ( "fmt" "reflect" ) func main() { x := 1 v := reflect.ValueOf(x) fmt.Println(v.CanSet()) v.SetInt(2) fmt.Println(x) }Predict the output. The value is reached through a pointer.
package main import ( "fmt" "reflect" ) type user struct { Name string age int } func main() { u := user{"ada", 36} v := reflect.ValueOf(&u).Elem() fmt.Println(v.Field(1).Int()) fmt.Println(v.Field(0).CanSet(), v.Field(1).CanSet()) v.Field(1).SetInt(37) }Predict the output: the type, then the kind.
package main import ( "fmt" "reflect" "time" ) type Celsius float64 func main() { for _, x := range []any{Celsius(21), 21.0, time.Second, []Celsius{}} { t := reflect.TypeOf(x) fmt.Println(t, t.Kind()) } }Predict the output.
package main import ( "fmt" "reflect" ) func main() { var err error var p *int fmt.Println(reflect.TypeOf(err)) fmt.Println(reflect.TypeFor[error]()) fmt.Println(reflect.TypeOf(p), reflect.ValueOf(p).IsNil()) fmt.Println(reflect.ValueOf(err).Kind(), reflect.ValueOf(err).IsValid()) }Predict the output.
package main import ( "fmt" "reflect" ) type T struct{} func (T) Get() {} func (*T) Set() {} func (T) hidden() {} func main() { T{}.hidden() fmt.Println(reflect.TypeFor[T]().NumMethod()) fmt.Println(reflect.TypeFor[*T]().NumMethod()) _, ok := reflect.TypeFor[T]().MethodByName("Set") fmt.Println(ok) }Predict the output.
package main import ( "fmt" "math" "reflect" ) func main() { var a []int b := []int{} fmt.Println(len(a) == len(b), reflect.DeepEqual(a, b)) n := math.NaN() fmt.Println(reflect.DeepEqual(n, n)) s := []float64{n} fmt.Println(reflect.DeepEqual(s, s)) }Predict the output.
package main import ( "encoding/json" "fmt" ) type T struct { A int `json:"a"` B int `json:"b,omitempty"` C int `json:"-"` D int `json:"-,"` E int f int } func main() { out, err := json.Marshal(T{A: 1, C: 3, D: 4, E: 5, f: 6}) fmt.Println(string(out), err) }Predict the output. Both slices are empty and not nil.
package main import ( "encoding/json" "fmt" "time" ) type Event struct { A time.Time `json:"a,omitempty"` B time.Time `json:"b,omitzero"` C []int `json:"c,omitempty"` D []int `json:"d,omitzero"` } func main() { out, err := json.Marshal(Event{C: []int{}, D: []int{}}) fmt.Println(string(out), err) }Predict the output.
package main import ( "fmt" "unsafe" ) func main() { big := make([]int, 1000) var ( s string a any m map[int]int e struct{} ) fmt.Println(len(big), unsafe.Sizeof(big), unsafe.Sizeof(s)) fmt.Println(unsafe.Sizeof(a), unsafe.Sizeof(m), unsafe.Sizeof(e)) }Predict the output.
package main import ( "fmt" "unsafe" ) type Head struct { _ struct{} N int64 } type Tail struct { N int64 _ struct{} } func main() { fmt.Println(unsafe.Sizeof(Head{}), unsafe.Sizeof(Tail{})) }Predict the output.
package main import ( "fmt" "unsafe" ) func main() { a := [4]int{1, 2, 3, 4} s := unsafe.Slice(&a[1], 2) fmt.Println(s, len(s), cap(s)) s[0] = 9 fmt.Println(a) t := a[1:3] fmt.Println(t, len(t), cap(t)) }Predict the output. Conv is a generic method.
package main import ( "fmt" "reflect" ) type Box struct{} func (Box) Plain() {} func (Box) Conv[T any](x T) T { return x } func main() { fmt.Println(Box{}.Conv(7)) t := reflect.TypeFor[Box]() fmt.Println(t.NumMethod()) for m := range t.Methods() { fmt.Println(m.Name) } }
- field read
- 1.0 ns direct; 3.4 ns by index; 46.7 ns by name.
- call
- 1.1 ns direct; 199 ns through reflect, with 2 allocations.
- json.Marshal
- 311 ns with a pointer and 1 allocation; 428 ns with a value and 3.
- string(b)
- 19.4 ns and 1 allocation for 32 bytes; 1.4 ns as a view.
- headers
- Slice 24 bytes, string 16, interface 16, map 8, on 64-bit.
- padding
- 16 to 32 bytes for the same 5 fields.
Go 1.27.3, 8-core Intel i9 laptop, GOMAXPROCS 16, median of 3 interleaved runs of 1 s, on a busy machine. Use these as orders of magnitude.