JSON Struct vs Map — Go Benchmark
Comparing JSON serialization performance between typed structs and generic maps (map[string]any).
When working with JSON in Go, you can either marshal and unmarshal into strongly typed structs or loosely typed maps (map[string]any). This benchmark compares the performance of both methods, covering both serialization (marshal) and deserialization (unmarshal). Strongly typed structs offer known type bounds for the reflections package, lowering runtime overhead and allocations.
1 CPU
32 CPUs
Struct Payload
Fastest (Marshal)Fastest (Unmarshal)Serializes and deserializes JSON using a strictly typed struct. This is the idiomatic way to handle JSON in Go. Because the fields and types are known in advance, it significantly reduces allocations and execution time while providing compile-time type safety.
Map Payload
Slowest (Marshal)Slowest (Unmarshal)Serializes and deserializes JSON using a dynamic map[string]any. While this approach is flexible and can handle arbitrary JSON shapes, it comes with a high overhead in execution time and heap allocations, as the standard library has to allocate map entries and parse types dynamically.
Contributors