zoukankan      html  css  js  c++  java
  • 《Delphi 算法与数据结构》学习与感悟[5]: 定位一个字符位置时, Pos 函数为什么不是最快的?

    如果 Pos 函数的第一个参数是 Char 而非 String, 那么编译器也会先把 Char 转换为 String;

    从内存结构到管理机制, String 远比 Char 要复杂.

    因此, 面对这种情况(要定位的是 Char) Pos 还有优化的余地; 优化后速度会提升 5 倍左右.

    测试效果图:


    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}
    
    //自定义的 Pos 函数
    function MyPos(c: Char; const str: string): Integer;
    var
      i: Integer;
    begin
      Result := 0;
      for i := 1 to Length(str) do
        if c = str[i] then begin Result := i; Exit end;
    end;
    
    {对比测试}
    procedure TForm1.Button1Click(Sender: TObject);
    var
      s: string;
      c: Char;
      i: Integer;
      n: Cardinal;
    begin
      s := 'abcdefghijklmnopqrstuvwxyz';
      Randomize;
      c := Chr(Random(26) + 97); {随机一个 a..z 的字符}
    
      {用 Pos 函数}
      n := GetTickCount;
      for i := 1 to 1000000 do Pos(c,s);
      n := GetTickCount - n;
      Text := IntToStr(n) + ' - ';
    
      {用自定义的 MyPos 函数}
      n := GetTickCount;
      for i := 1 to 1000000 do MyPos(c,s);
      n := GetTickCount - n;
      Text := Text + IntToStr(n);
    
      Button1.Caption := 'Pos 与 MyPos 速度测试';
    end;
    
    end.
    
  • 相关阅读:
    进程和线程
    yum安装apache后更改worker模式
    (转)top命令详解
    虚拟机linux在关机不正常的情况下出现的问题
    mysql赋予用户权限grant all privileges on
    lampp自带mysql远程访问问题
    扫盲
    linux常用命令使用
    剑指Offer对答如流系列
    剑指Offer对答如流系列
  • 原文地址:https://www.cnblogs.com/del/p/1111340.html
Copyright © 2011-2022 走看看