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

Dar*_*arx 6 delphi overloading

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

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

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

jac*_*ate 19

当然,你可以肯定,因为它是记录在案的.编译器是否在编译时解析它,因此在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;
Run Code Online (Sandbox Code Playgroud)

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

替代文字

  • 编译后的代码不关心名称,而是关注正确调用过程的地址.由于此转换名称=>地址是在编译时完成的,最后在运行时完成与具有不同名称的完全相同. (2认同)