This benchmark measures performance of various alternatives to interface cast, which is expensive.
The reason is that interface cast involves "duct type check", and cast to type just checks a type hash value inside iface.
Cases:
BenchmarkAssertStruct- Castanyto a concrete struct type (fastest).BenchmarkAssertIface- Cast to an interface.BenchmarkAssertWrapper- Cast to a concrete type and call a field that is an interface.BenchmarkAssertClosure- Cast to a concrete type and call a closure func field.
goos: js
goarch: wasm
pkg: main
BenchmarkAssertIface
BenchmarkAssertIface 28571341 36.54 ns/op
BenchmarkAssertStruct
BenchmarkAssertStruct 85713501 12.58 ns/op
BenchmarkAssertWrapper
BenchmarkAssertWrapper 49999999 21.42 ns/op
BenchmarkAssertClosure
BenchmarkAssertClosure 57143030 21.12 ns/op
PASS
See playground here
goos: linux
goarch: amd64
pkg: main
cpu: AMD Ryzen 5 7600X 6-Core Processor
BenchmarkAssertIface-12 1000000000 5.597 ns/op
BenchmarkAssertStruct-12 1000000000 3.412 ns/op
BenchmarkAssertWrapper-12 1000000000 5.702 ns/op
BenchmarkAssertClosure-12 1000000000 5.668 ns/op
PASS
goos: linux
goarch: amd64
pkg: main
cpu: AMD EPYC-Rome Processor
BenchmarkAssertIface-2 1000000000 12.68 ns/op
BenchmarkAssertStruct-2 1000000000 6.342 ns/op
BenchmarkAssertWrapper-2 1000000000 12.55 ns/op
BenchmarkAssertClosure-2 1000000000 10.61 ns/op
PASS
Concrete type cast is the fastest path. Any attempts to "optimize" strict interface cast by introducing wrappers (BenchmarkAssertClosure and BenchmarkAssertWrapper) did not introduce any impactuful perf improvements (except WASM).