测试一下性能
发现 对比 TList + TSpinLock(自旋锁的方式差距很大);
unit Unit2;
interface
uses
Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics,
Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls, System.Generics.Collections, System.SyncObjs;
type
TForm2 = class(TForm)
Button1: TButton;
Memo1: TMemo;
Button2: TButton;
Button3: TButton;
procedure Button1Click(Sender: TObject);
procedure FormCreate(Sender: TObject);
procedure FormClose(Sender: TObject; var Action: TCloseAction);
procedure Button2Click(Sender: TObject);
procedure Button3Click(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;
TMyThread = class(TThread)
protected
procedure Execute; override;
end;
TMyThread2 = class(TThread)
protected
procedure Execute; override;
end;
var
Form2: TForm2;
lock: TSpinLock;
list: TList<string>;
list2: TThreadList<string>;
implementation
{$R *.dfm}
procedure TMyThread.Execute;
var
I: Integer;
start, take: UInt64;
begin
start := GetTickCount64;
for I := 0 to 10000 do
begin
lock.Enter;
list.Add(TGUID.NewGuid.ToString);
lock.Exit();
end;
take := GetTickCount64 - start;
OutputDebugString(PChar('耗时:' + take.ToString));
end;
procedure TMyThread2.Execute;
var
I: Integer;
start, take: UInt64;
begin
start := GetTickCount64;
for I := 0 to 10000 do
begin
list2.Add(TGUID.NewGuid.ToString);
end;
take := GetTickCount64 - start;
OutputDebugString(PChar('耗时:' + take.ToString));
end;
procedure TForm2.Button1Click(Sender: TObject);
var
th1, th2, th3: TMyThread;
begin
list.Clear;
th1 := TMyThread.Create;
th1.FreeOnTerminate := True;
th2 := TMyThread.Create;
th2.FreeOnTerminate := True;
th3 := TMyThread.Create;
th3.FreeOnTerminate := True;
end;
procedure TForm2.Button2Click(Sender: TObject);
begin
ShowMessage(list.Count.ToString);
end;
procedure TForm2.Button3Click(Sender: TObject);
var
th1, th2, th3: TMyThread2;
begin
list2.Clear;
th1 := TMyThread2.Create;
th1.FreeOnTerminate := True;
th2 := TMyThread2.Create;
th2.FreeOnTerminate := True;
th3 := TMyThread2.Create;
th3.FreeOnTerminate := True;
end;
procedure TForm2.FormClose(Sender: TObject; var Action: TCloseAction);
begin
list.Free;
list2.Free;
end;
procedure TForm2.FormCreate(Sender: TObject);
begin
list := TList<string>.Create;
list2 := TThreadList<string>.Create;
//list2.Duplicates := dupAccept; TThreadList默认开启了 去重,导致性能极低;
ReportMemoryLeaksOnShutdown := True;
end;
end.
是什么原因呢,后来 看了下 官方的文档 发现 这个 多线程容器 默认去重了,导致耗时很大;
先试验下 是否默认 去重了:
··· c
procedure TForm2.Button4Click(Sender: TObject);
var
ls: TList;
ls2: TThreadList;
begin
ls := TList.Create;
ls2 := TThreadList.Create;
try
ls.Add(‘a’);
ls.Add(‘a’);
ShowMessage(ls.Count.ToString);
ls2.Add('a');
ls2.Add('a');
ShowMessage(ls2.LockList.Sort.ToString);
finally
list.Free;
list2.Free;
end;
end;