《Delphi 算法与数据结构》: 关于 const

如果参数在函数中不可能修改, 一定要使用 const;

不然, 编译器就会:
假定先修改, 先要备份; 使用前后要增减引用计数; 还要套上 try finally.

指定了 const 就可以避免以上过程从而提高效率.

 

unit

 Unit1;

interface

uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls;

type
TForm1 = class (TForm)
Button1: TButton;
procedure Button1Click(Sender: TObject);
end ;

var
Form1: TForm1;

implementation

{$R *.dfm}

//判断一个字符串中数字的个数
function GetNum1(str: string ): Integer;
var
i: Integer;
begin
Result := 0 ;
for i := 1 to Length(str) do
if str[i] in ['0' ..'9' ] then Inc(Result);
end ;

//同样的函数只是给参数加上 const
function GetNum2(const str: string ): Integer;
var
i: Integer;
begin
Result := 0 ;
for i := 1 to Length(str) do
if str[i] in ['0' ..'9' ] then Inc(Result);
end ;

{对比测试}
procedure TForm1.Button1Click(Sender: TObject);
var
s: string ;
n: Cardinal;
i: Integer;
begin
s := 'ABC123' ;

n := GetTickCount;
for i := 0 to 1000000 do GetNum1(s);
n := GetTickCount - n;
Text := IntToStr(n) + ' - ' ;

n := GetTickCount;
for i := 0 to 1000000 do GetNum2(s);
n := GetTickCount - n;
Text := Text + IntToStr(n);
end ;

end .
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值