Delphi XE4中Or, In, CharInSet,哪个更快?

在Delphi XE4中测试用Or,In,CharInSet三种方式,实现判断一个字符是否在一个字符数组中。
作者提供了代码:

procedure TForm7.FormCreate(Sender: TObject);
const
  Max = 200000000;
var
  S       : AnsiString;
  PBuffer : PByte;
  Count   : Integer;
  I       : Integer;
  pf      : int64;
  st      : int64;
  et      : int64;
begin
  WinApi.Windows.QueryPerformanceFrequency( pf );//获得机器内部定时器的时钟频率

  SetLength( S, Max );
  for I := 1 to Max do S[i] := AnsiChar( random(128-32) 31 );

  WinApi.Windows.QueryPerformanceCounter( st );//取得开始值
  Count := 0;
  PBuffer := @S[1];
  while PAnsiChar(PBuffer)^<>#0 do begin
    if (PAnsiChar(PBuffer)^='M')
    or (PAnsiChar(PBuffer)^='Z')
    or (PAnsiChar(PBuffer)^='x')
    or (PAnsiChar(PBuffer)^='y')
    or (PAnsiChar(PBuffer)^='*')
    then
      Inc(Count);
    Inc( PBuffer );
  end;
  WinApi.Windows.QueryPerformanceCounter( et );//取得结束值
  Caption := Format('%s, or:%d-%f',[Caption,Count, (et-st) / pf]);//计算出耗用的时长单位为秒

  WinApi.Windows.QueryPerformanceCounter( st );
  Count := 0;
  PBuffer := @S[1];
  while PAnsiChar(PBuffer)^<>#0 do begin
    if PAnsiChar(PBuffer)^ in ['M','Z','x','y','*']
    then
      Inc(Count);
    Inc( PBuffer );
  end;
  WinApi.Windows.QueryPerformanceCounter( et );
  Caption := Format('%s, in:%d-%f',[Caption,Count, (et-st) / pf]);

  WinApi.Windows.QueryPerformanceCounter( st );
  Count := 0;
  PBuffer := @S[1];
  while PAnsiChar(PBuffer)^<>#0 do begin
    if CharInSet( PAnsiChar(PBuffer)^, ['M','Z','x','y','*'] )
    then
      Inc(Count);
    Inc( PBuffer );
  end;
  WinApi.Windows.QueryPerformanceCounter( et );
  Caption := Format('%s, fn:%d-%f',[Caption,Count, (et-st) / pf]);

end;

得出的结论是用IN的方式最快,其次是OR,最愉的是用函数CharInSet。
Delphi <wbr>XE4中Or, <wbr>In, <wbr>CharInSet,哪个更快?

看后我也用这个代码试了一下,情况与上面不同:
在Debug状态下:
Delphi <wbr>XE4中Or, <wbr>In, <wbr>CharInSet,哪个更快?

在Release状态下:
Delphi <wbr>XE4中Or, <wbr>In, <wbr>CharInSet,哪个更快?

在两种状态下,结果是不一样的,此外,在Release状态下,与原作者也有些偏差。你也一起来试试,看看是什么样的结果?


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值