巧用stringbuilder,加快字符串读写和UI重画的速度
在字符串的读写中,人们常用的是string,但是在多个字符串连接的时候,因为需要在每次连接时,重新生成一个字符串,因此,速度非常慢。
而stringbuilder在处理字符串的时候,是在字符串地址上直接操作,增加或者删除都是通过指针,因此速度异常快。下面,我就用一个例子来说明一下。
实践证明,字符串直接操作,要比stringbuilder慢20倍,这还只是50000个字符串,要是更多,将会更加慢。不过,在UI显示的时候,字符串数量越大,差别越不明显,这是因为UI显示在整体实践占的比重比较大。
代码如下:
unit Unit10;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls,DateUtils;
type
TForm10 = class(TForm)
ListBox1: TListBox;
Button1: TButton;
Button2: TButton;
Label1: TLabel;
procedure Button1Click(Sender: TObject);
procedure Button2Click(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;
var
Form10: TForm10;
implementation
{$R *.dfm}
procedure TForm10.Button1Click(Sender: TObject);
var
I: Integer;
starttime,endtime:TTime;
begin
starttime:=Now;
for I := 0 to 50000 - 1 do
begin
ListBox1.Items.Add(IntToStr(i)) ;
end;
endtime:=Now;
Label1.Caption:=Format('耗用的时间(毫秒):%f',[millisecondspan(starttime,endtime)]);
end;
procedure TForm10.Button2Click(Sender: TObject);
var
str: TStringBuilder;
I: Integer;
starttime, endtime: TTime;
begin
starttime := Now;
str := TStringBuilder.Create;
ListBox1.Items.Clear;
for I := 0 to 50000 - 1 do
begin
// if i=4999 then
// str.AppendFormat('%s',[inttostr(i)]);
str.AppendFormat('%s,', [IntToStr(I)]);
end;
// ListBox1.Items.CommaText:=str.ToString;
ListBox1.Items.Delimiter := ',';
ListBox1.Items.DelimitedText := str.ToString;
ListBox1.Items.Delete(ListBox1.Items.Count - 1);
endtime := Now;
Label1.Caption:=Format('耗用的时间(毫秒):%f',[millisecondspan(starttime,endtime)]);
end;
end.