2

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?

user1580348
  • 5,721
  • 4
  • 43
  • 105
  • 1
    Code looks fine and the program should not hang. It is impossible to say why without a reproducible test case. And, of course it works slower if you send information to CodeSite in each loop. – gabr Jun 13 '18 at 10:55
  • Might be slower because it takes time to set up the background threads. SO making it work parallel would only benefit for large lists. Moreover I worry about the slTempSearchList, if it is shared between threads you'll run into serious race condition problems. – H.Hasenack Jun 12 '20 at 12:53

0 Answers0