Question:
Since TDictionary
only exposes ways to retrieve value via 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 hold an average of 50 items.
-
It would also be valid to replace this structure with any other.
And so my question: is there a way to perform the same task with better performance in terms of execution speed?
Answer:
Updated 06/26/2016
Guill, you can use a TPair
to traverse and find the value you need more 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 your search.
Take a look at this link too, it contains a more detailed explanation : Delphi TDictionary iteration