How to improve the performance of a key search?

Asked

Viewed 258 times

3

In view of the fact that TDictionary exposes only ways to recover value through the key, I have the following algorithm to fetch a key from its value:

var
    Table: TDictionary<Int64, Extended>;

function KeyOf(Value: Extended): Int64; inline;
var
    Key: Int64;
begin
    Result := -1;
    if not Table.ContainsValue(Value) then
        Exit;
    for Key in Table.Keys do
        if Table.Items[Key] = Value then
        begin
            Result := Key;
            Exit;
        end;
end;
  • I’m calling this function in a loop that runs at least 50,000 times.

  • I need to keep indexing by integers that do not repeat.

  • During execution the structure will hold on average 50 items.

  • It would also be valid to replace this structure with any other.

And then my question: is there a way to accomplish the same task with better performance as to the speed of execution?

1 answer

1

Updated 26/06/2016

Guill, you can use a TPair to browse and find the value you need most efficiently.

function KeyOf(Value: Extended): Int64; inline;
var
  vIterator: TPair<Int64, Extended>;
begin
  Result := -1;
  if not Table.ContainsValue(Value) then
    Exit;

  for vIterator in Table do
  begin
    if vIterator.Value = Value then
    begin
      Result := vIterator.Key;
      break;
    end;
  end;
end;

You can test with your records and check if there is an improvement in the search.


Take a read on this link too, contains a more detailed explanation: Delphi Tdictionary iteration

  • Would not be TPair?

  • You’re right, I edited the answer with the correction, thank you

  • But there was no significant improvement. Although it has made it possibly faster.

  • In the case of TDictionary I believe that the best search option would be this. Tell me the purpose of its use with the TDictionary, maybe we can consider other structures more flexible.

  • It’s a very specific use. I have a array of objects. A Table shall contain entries associated with a value Extended the content of certain objects contained in array mentioned. The utility of the algorithm is to check if there is already an object associated with the corresponding value. Only one entry of each object and one entry of each distinct value should be possible.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.