Thursday, March 19, 2009

Delphi 2009 string type performance benchmark

This code was run on a Intel Core 2 laptop, and shows the difference in performance very well. Compiler options used: Code optimization disabled, all checks on.


procedure TForm3.Button3Click(Sender: TObject);
var
a:ansistring;
r:rawbytestring;
u:string;
w:widestring;
i:integer;
s:shortstring;
c:char; // widechar
ac:ansichar;
begin
screen.Cursor:=crHourGlass;
try
// approx. 222 million iterations per second
s:='This is a test';
for i:=0 to 1000000000 do begin
ac:=s[4];
s[4]:=s[5];
s[5]:=ac;
end;

// approx. 43 million iterations per second
a:='This is a test';
for i:=0 to 1000000000 do begin
ac:=a[4];
a[4]:=a[5];
a[5]:=ac;
end;

// approx. 40 million iterations per second
u:='This is a test';
for i:=0 to 1000000000 do begin
c:=u[4];
u[4]:=u[5];
u[5]:=c;
end;

// approx. 71 million iterations per second
w:='This is a test';
for i:=0 to 1000000000 do begin
c:=w[4];
w[4]:=w[5];
w[5]:=c;
end;

// ****************************

// approx. 40 million iterations per second
for i:=0 to 100000000 do begin
u:='This is € test';
end;

// approx. 5.5 million iterations per second
for i:=0 to 100000000 do begin
a:='This is € test';
u:=a;
end;

// approx. 5.5 million iterations per second
for i:=0 to 100000000 do begin
u:='This is € test';
a:=u;
end;

// approx. 3.7 million iterations per second
for i:=0 to 100000000 do begin
u:='This is € test';
w:=u;
end;

// ****************************

// approx. 3.7 million iterations per second
s:='';
for i:=0 to 100000000 do begin
s:=copy(s+' ',1,50);
end;

// approx. 4.2 million iterations per second
a:='';
for i:=0 to 100000000 do begin
a:=copy(a+' ',1,50);
end;

// approx. 2.5 million iterations per second
u:='';
for i:=0 to 100000000 do begin
u:=copy(u+' ',1,50);
end;

// approx. 1.6 million iterations per second
w:='';
for i:=0 to 10000000 do begin
w:=copy(w+' ',1,50);
end;

// ****************************

// approx. 25 million iterations per second
r:='';
for i:=0 to 100000000 do begin
r:=r+' ';
end;

// approx. 25 million iterations per second
a:='';
for i:=0 to 100000000 do begin
a:=a+' ';
end;

// approx. 25 million iterations per second
u:='';
for i:=0 to 100000000 do begin
u:=u+' ';
end;

// approx. 0.0055 million iterations per second
w:='';
for i:=0 to 100000 do begin
w:=w+' ';
end;
finally
screen.Cursor:=crDefault;
end;
end;


Conclusion:
* Avoid widestring and shortstring.
* UnicodeString is a huge improvement to WideString.

No comments: