Parallel.For takes longer than for loop

128 Views Asked by At

In Delphi Berlin 10.1, I have a for loop:

for i := 0 to slSMP.Count - 1 do
begin
  if System.StrUtils.Containstext(slSMP.ValueFromIndex[i], ThisSearchTerm) or
    System.StrUtils.Containstext(ExtractFileName(ExcludeTrailingPathDelimiter(slSMP.Names[i])), ThisSearchTerm) then
  begin
    slTempSearchList.Add(slSMP.Names[i] + slSMP.ValueFromIndex[i]);
  end;
end;

slSMP and slTempSearchList obviously are of type TStringList.

Unfortunately, this loop takes too much time, so I decided to transform it into a OtlParallel.Parallel.For loop:

OtlParallel.Parallel.For(0, slSMP.Count - 1).Execute(
  procedure (i: integer)
  begin
    if System.StrUtils.Containstext(slSMP.ValueFromIndex[i], ThisSearchTerm) or
      System.StrUtils.Containstext(ExtractFileName(ExcludeTrailingPathDelimiter(slSMP.Names[i])), ThisSearchTerm) then
    begin
      slTempSearchList.Add(slSMP.Names[i] + slSMP.ValueFromIndex[i]);
      //CodeSite.Send('TformSearchStartMenu.DoSearchFromSearchEdit: i', i);
    end;
  end);

STRANGELY, when the CodeSite.Send line is DEACTIVATED, this loop never finishes, so I had to close the application with the task manager.

But when the CodeSite.Send line is ACTIVATED, the loop finishes, but it takes LONGER than the simple for loop.

So how can I make this loop faster with parallel programming?
  And why does the OtlParallel.Parallel.For only work when the CodeSite.Send line is ACTIVATED? How can I make it work without the CodeSite.Send line?

0

There are 0 best solutions below