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

来源:互联网 发布:医药研发待遇知乎 编辑:程序博客网 时间:2024/05/05 17:47
在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状态下,与原作者也有些偏差。你也一起来试试,看看是什么样的结果?


0 0
原创粉丝点击