函数重载是否在Delphi中具有运行时开销?

时间:2010-09-28 19:07:24

标签: delphi overloading

调用重载函数是否还有额外的运行时开销?

(我特意问Delphi,以防所有编译语言的答案都不一样)

我认为不应该在编译期间解决这个问题,但是你永远无法确定吗?

2 个答案:

答案 0 :(得分:19)

当然你可以肯定,因为它是documented。编译器是否在编译时解析它,因此在Delphi中调用重载函数没有额外的开销。

[编辑]

我为你做了一个小测试:

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;

结果:在我的开发机器上几乎所有时间都是31 Ticks(毫秒),有时重载只需要16个滴答。

alt text

答案 1 :(得分:3)

重载在编译时解决(没有开销),但覆盖有开销! virtualdynamic

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

  

虚拟与动态
  在Delphi for Win32中,虚拟和动态方法在语义上是等效的   但是,它们在运行时方法调用调度的实现方面有所不同:虚拟方法优化速度,而动态方法优化代码大小。