How to improve the performance of a key search?

3

Given that TDictionary exposes only ways to retrieve 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 for non-repeating integers.

  • During execution, the structure will behave on average 50 items.

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

And so my question: is there a way to accomplish the same task with the best execution speed performance?

    
asked by anonymous 25.06.2016 / 02:32

1 answer

1

Updated 06/26/2016

Guill, you can use TPair to scroll 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 your records and see if there is an improvement in the search.

Please read this link as well, it contains a more detailed explanation : Delphi TDictionary iteration

    
25.06.2016 / 04:11