This is a creation in Article, where the information may have evolved or changed.
Reprinted from Dada's blog
In some generalized interface designs, we have to use interface{} to represent any type, and then use type conversions inside the interface to determine the specific type, thus executing the specific logic. But the type judgment has the performance cost, if can have the image to know how this performance cost is big, can help us to design the interface time to judge how should design.
Here's the Experiment Code (GitHub):
PackageLabs01Import "Testing"typeInterfaceaInterface{AA ()}typeInterfacebInterface{BB ()}typeAstruct{Vint}func(A *a) AA () {A.V + =1}typeBstruct{Vint}func(b *b) BB () {B.V + =1}funcTypeswitch (vInterface{}) {SwitchV. (type) { CaseInterfacea:v. (interfacea). AA () CaseInterfaceb:v. (INTERFACEB). BB ()}}funcNormalswitch (a *a) {A.aa ()}funcInterfaceswitch (vInterface{}) {V. (INTERFACEA). AA ()}funcBenchmark_typeswitch (b *testing. B) {varA =NewA forI: =0; i < B.N; i++ {Typeswitch (a)}}funcBenchmark_normalswitch (b *testing. B) {varA =NewA forI: =0; i < B.N; i++ {Normalswitch (a)}}funcBenchmark_interfaceswitch (b *testing. B) {varA =NewA forI: =0; i < B.N; i++ {Interfaceswitch (a)}}
Execution Result:
Dada-imac:misc dada$ Go test-test.bench= ". *" Labs01testing:warning:no tests to Runpassbenchmark_typeswitch 50000000 33.0 ns/opbenchmark_normalswitch 2000000000 1.99 ns/opbenchmark_interfaceswitch 100000000 18.4 ns/opok Labs 7.741s
Conclusion: Both the type judgment and the type conversion are consumed several times more than the direct operation.