views:

238

answers:

2

Is there any additional runtime overhead in calling overloaded functions?

(I ask this specifically for Delphi, in case the answer isn't the same for all compiled languages)

I think not as that should be resolved during compile time, but you can never be sure can you?

+20  A: 

Of course you can be sure, because it is documented. Is the compiler which resolves it at compile time, so there's no additional overhead on calling overloaded functions in Delphi.

[Edit]

I did a small test for you:

var
  j: Integer;
  st: string;

procedure DoNothing(i: Integer); overload;
begin
  j := i;
end;

procedure DoNothing(s: string); overload;
begin
  st := s;
end;

procedure DoNothingI(i: integer);
begin
  j := i;
end;

procedure TForm2.Button1Click(Sender: TObject);
const
  MaxIterations = 10000000;
var
  StartTick, EndTick: Cardinal;
  I: Integer;
begin
  StartTick := GetTickCount;
  for I := 0 to MaxIterations - 1 do
    DoNothing(I);
  EndTick := GetTickCount;
  Label1.Caption := Format('Overlaod ellapsed ticks: %d [j:%d]', [EndTick - StartTick, j]);
  StartTick := GetTickCount;
  for I := 0 to MaxIterations - 1 do
    DoNothingI(I);
  EndTick := GetTickCount;
  Label1.Caption := Format('%s'#13'Normal ellapsed ticks: %d [j:%d]', [Label1.Caption, EndTick - StartTick, j]);
end;

Result: Almost all the time 31 Ticks (milliseconds) for both on my dev machine, sometimes overload takes only 16 ticks.

alt text

jachguate
+1 you beat me to it :)
Marjan Venema
Right. There's a (negligible) amount of compile-time overhead, but none at runtime.
Mason Wheeler
The compiled code does not care about the name but the address of the right procedure to call. Since this translation name => address is done at compile time, in the end, at run time, it is exactly the same as having different names.
François
Don't use tickcount! Because most time functions works in steps of 15ms! E.g. sleep(1) = 15ms, but also the Now() function! That's why sometimes 31 ticks and sometimes 16 ticks.
André
Better use QueryPerformanceCounter, this one is the best (about 3Mhz) so you can count microseconds
André
@André: `GetTickCount()` is perfectly fine for such quick tests, provided the measured time is large compared to the resolution (just make `MaxIterations` large enough to result in a few 100 ms runtime).
mghie
+3  A: 

Overloading is resolved at compile time (no overhead), but overriding has overhead! virtual is faster than dynamic:

http://docwiki.embarcadero.com/RADStudio/en/Methods

Virtual versus Dynamic
In Delphi for Win32, virtual and dynamic methods are semantically equivalent.
However, they differ in the implementation of method-call dispatching at run time: virtual methods optimize for speed, while dynamic methods optimize for code size.

André