On Fri, Dec 1, 2017 at 2:40 AM, Ugorji Nwoke <ugo...@gmail.com> wrote:
>
> I know that a no-op function call is optimized away, as it is inlined to
> nothing.
>
> However, what about a no-op interface call?
>
> See sample code:
>
> type I interface { Do(int) }
> type T1 struct{}
> func (_ T1) Do(i int) {}
> func main() {
> var v I
> v = T1{}
> v.Do(1)
> }
>
> Is it safe to assume the following that calling T1.Do(...) via an interface
> costs a dereference + jump (but NO function call overhead)?
>
> I currently have code where I do a lot of conditional checks to determine
> whether to make that interface call or not.
> However, if I know that the no function call overhead is done when the
> dynamic function is a no-op, then I will just call the interface
> method all the time, and not try to be smart within code.
>
> I tried looking at "go tool compile -S main.go" output, but I still see a
> CALL in there, but don't know whether the linker/compiler/something
> optimizes this out.

In general, no.  The compiler doesn't currently try to figure out the
dynamic type of an interface (an optimization known as
devirtualization).  An interface method can only be inlined when the
dynamic type is known.

The cost of calling an empty method is quite low.  It's not zero, but
I am skeptical that the cost of the call is more than the cost of the
conditional checks you mention.

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 golang-nuts+unsubscr...@googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

Reply via email to