On Mon, Oct 15, 2012 at 9:46 PM, Erwin wrote:
Anyway, what I am really curious about is if it is possible (at some future
point in time) that a function taking interface parameters performs equally
fast as a function taking concrete type parameters. That would be cool, to
be able to rely on that.
The short answer is that it is not possible to rely on this. A call
through an interface cannot be guaranteed to take the same time as a
direct function/method call, aside through slowing down function
calls.
This is because a direct call to a function can be done as a simple
call to a compile-time known function. A method call through an
interface requires looking up the function to call in a table
referenced by the interface value, then doing a call to it. The former
permits, in many cases, a faster implementation, and never requires a
slower implementation.
You can think, somewhat loosely, of a direct call as equivalent to a
call through an interface for which the compiler has more information
statically available, and so can generate more optimised executable
code. It is equivalent to the difference in C++ between direct
function calls and virtual method calls.
The actual difference may vary with optimisation, as the
implementation could try to convert calls through interfaces to direct
calls when it can statically recognise what type the value in the
interface must be, removing the method lookup and permitting inlining.
I do not believe you will be able to expect this to happen reliably in
the foreseeable future, however.
All that said, unless your functions are doing barely any work, call
overhead should be small, and the additional overhead from the method
lookup even smaller. Both function and interface calls in Go easily
outperform all function calls in languages which require looking up
called functions at runtime, or otherwise don't compile function calls
to a direct call. Such languages may permit functions and methods to
take the same amount of time, but only by making calling both much
slower.
You shouldn't worry about method lookup overhead unless profiling is
directing you to optimise a part of your code, because avoiding it is
likely to have high maintainability costs with near-zero performance
improvement in most places.
--