Are there any advantages in using const parameters with an ordinal type?

前端 未结 5 1944
失恋的感觉
失恋的感觉 2020-12-05 06:54

I know marking string parameters as const can make a huge performance difference, but what about ordinal types? Do I gain anything by making them const

5条回答
  •  挽巷
    挽巷 (楼主)
    2020-12-05 07:09

    There's a huge speed improvement using Const with strings:

    function test(k: string): string;
    begin
      Result := k;
    end;
    
    function test2(Const k: string): string;
    begin
      Result := k;
    end;
    
    function test3(Var k: string): string;
    begin
      Result := k;
    end;
    
    procedure TForm1.Button1Click(Sender: TObject);
    Var a: Integer;
        s,b: string;
        x: Int64;
    begin
      s := 'jkdfjklf lkjj3i2ej39ijkl  jkl2eje23 io3je32 e832 eu283 89389e3jio3 j938j 839 d983j9';
    
      PerfTimerInit;
      for a := 1 to 10000000 do
       b := test(s);
      x := PerfTimerStopMS;
      Memo1.Lines.Add('default: '+x.ToString);
    
      PerfTimerInit;
      for a := 1 to 10000000 do
       b := test2(s);
      x := PerfTimerStopMS;
      Memo1.Lines.Add('const: '+x.ToString);
    
      PerfTimerInit;
      for a := 1 to 10000000 do
       b := test3(s);
      x := PerfTimerStopMS;
      Memo1.Lines.Add('var: '+x.ToString);
    end;
    

    default: 443 const: 320 var: 325

    default: 444 const: 303 var: 310

    default: 444 const: 302 var: 305

    Same with Integers:

    default: 142 const: 13 var: 14

    Interestingly though, in 64-bit there seems to be almost no difference with strings (default mode is only a bit slower than Const):

    default: 352 const: 313 var: 314

提交回复
热议问题