Consider this very simple piece of code:
uses Diagnostics;
const
ITER_COUNT = 100000000;
procedure TForm1.btn2Click(Sender: TObject);
var
val: Double;
i: Integer;
begin
sw := TStopwatch.StartNew;
val := 1;
for i := 0 to ITER_COUNT - 1 do
begin
val := val + i;
val := val - i;
val := val * 10;
val := val / 10;
end;
sw.Stop;
mmo1.Lines.Add(Format('Simple completed in %D ms. Result: %G',
[sw.ElapsedMilliseconds, val]));
end;
This simple loop executes in 4027 ms on my PC. Now if I write the same code, only using different thread:
procedure TForm1.btn3Click(Sender: TObject);
begin
sw := TStopwatch.StartNew;
TThread.CreateAnonymousThread(
procedure
var
val: Double;
i: Integer;
begin
val := 1;
for i := 0 to ITER_COUNT- 1 do
begin
val := val + i;
val := val - i;
val := val * 10;
val := val / 10;
end;
sw.Stop;
TThread.Queue(nil, procedure
begin
mmo1.Lines.Add(Format('Async completed in %D ms. Result: %G',
[sw.ElapsedMilliseconds, val]));
end);
end
).Start;
end;
This method which does the same but in the different thread executes in 2910 ms! (Compiled in Delphi XE with Release configuration active) I noticed ~25% gain in the thread no matter how many iterations I have. Why this is so? Shouldn't it be the same results?
EDIT: After further investigations I found that probably the reason for this is Windows 7 OS. On Windows 7 machine simple loop in the main thread executes ~25% slower than async version! I've even tried to run this same project on the same Windows 7 PC using Windows XP mode and then both results were equal - ~3000ms! I'm completely lost here...What is Windows 7 doing with the main thread that it is slower?