Go language Type Assertion performance test

Source: Internet
Author: User
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.


Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.