Thursday, 16 October 2008

Widestring 4545 times slower than unicodestring

I noticed that several people, in comments and in other blogs, compared the number of seconds that was spent for each benchmark in my previous post. I presented both the time spent, the number of iterations and the number of iterations per second, and it is the last number that is interesting. In order to fix that, I have now removed the time measurements from that post.

For that same reason, several people wondered why I did not like widestring. The main reason why I recommend not to use widestring is this one:

// 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;


Note, how widestring is extremely slow for this specific test. This is the kind of stuff that can make a well made application perform really bad. A TCP/IP ping request between two servers on a good network uses less time than it takes to add a space to a widestring on my reasonably fast laptop.

3 comments:

gabr said...

Well, this is a code that should never appear in a well-written application.

I do agre that converting old apps that use this kind of code is a problem - but then I'm not planning to convert old applications at all. New developement will start as Unicode apps, old ones will stay Ansi.

Anonymous said...

Fragmentation is obviously going to happen in code of this nature, and with a widestring it will happen sooner. Just by pre-setting the reserved memory for the string will already help.

Understanding what is happening in the background is the key to writing an appropriate algorithm.

stanleyxu (2nd) said...

Yes. This is one of the most important reasons, why we should move to Delphi 2009