On Wed, Dec 30, 2020 at 9:52 AM Arnaud Delobelle <[email protected]> wrote: > > Thanks for the explanations. Given reflect and the plugin mechanism, it > seems like compile time analysis is not a very attractive option. It is a > shame in my case because I really feel like using an interface is the natural > solution to my problem in Go, but the runtime cost of type assertion is too > high for me to ignore (which means I can still use interfaces but need to > work around type assertion).
Just to stress what you already know, type assertions to non-interface types are fast. What is (relatively) slow is type assertions to interface types. The same guideline applies to type switches. So if you have a fixed set of possible types, consider using type switches to all possible types that implement the interface you want, rather than doing a type assertion to the interface type. > Another possibility may be that at the first type assertion x.(I), the > runtime learns that the concrete type of x satisfies interface I, so that > next time an interface value with the same concrete type as x is coerced to > I, it can take a short path. I don't know enough about the runtime to know > whether that is feasible at all! The runtime already does this, but the fast path still requires doing a lookup in a hash table and an atomic load. So it's still going to be measurably slower than a type assertion to a non-interface type, which only requires a pointer comparison. Ian -- You received this message because you are subscribed to the Google Groups "golang-nuts" group. To unsubscribe from this group and stop receiving emails from it, send an email to [email protected]. To view this discussion on the web visit https://groups.google.com/d/msgid/golang-nuts/CAOyqgcW0RggVOKnQ2KGyxoPCdP90NhxPn0JBcy0aKfO%3DkJm5jw%40mail.gmail.com.
