Type Discovery Performance in Go: Are Type Assertions / Type Switches Slow?
In Go, type discovery at runtime can be achieved through type assertions or type switches. While type assertion performs a direct cast, type switch compares against type information. In C/C , runtime type discovery is often considered slow, leading to the use of type member comparisons as a workaround.
Evaluating Performance with Benchmarking
To assess the performance of type discovery mechanisms in Go, we conduct a benchmark test: http://play.golang.org/p/E9H_4K2J9-. The test compares four methods:
Benchmark Results
Edit: October 09, 2019
Recent results with Go v1.12.9 on an AMD R7 2700X demonstrate that the four methods are approximately equal in performance:
BenchmarkIntmethod-16 2000000000 1.67 ns/op BenchmarkInterface-16 1000000000 2.03 ns/op BenchmarkTypeSwitch-16 2000000000 1.70 ns/op BenchmarkTypeAssertion-16 2000000000 1.67 ns/op
Previous Results: January 19, 2015
On an amd64 machine, older results showed that type switch and type assertion were slower than direct method calls or interface method invocations:
BenchmarkIntmethod 1000000000 2.71 ns/op BenchmarkInterface 1000000000 2.98 ns/op BenchmarkTypeSwitch 100000000 16.7 ns/op BenchmarkTypeAssertion 100000000 13.8 ns/op
Conclusion
Based on these results, it can be concluded that type assertions and type switches in Go do not have a significant performance penalty compared to other type checking methodologies. Therefore, selecting the most appropriate approach depends on factors such as code readability and maintenance preferences.
The above is the detailed content of Are Go's Type Assertions and Type Switches Slow?. For more information, please follow other related articles on the PHP Chinese website!