I am using a hashset structure for mapping purposes: Dictionary<string, string>.
If I need to read the value of myHashset[“key1”] many times in successive statements, is it a good practice to store the first lookup using a local variable?
Edit: no other thread would modify the dictionary so it is not an important criterion.
Thanks!
Yes.
O(1)simply states that the operation takes the same amount of time, no matter how many items are there.This doesn’t mean, that the time it takes is as fast as simply accessing a local variable.
Additionally, consider the following:
TryGetValuewhen accessing a value in a dictionary by its key. When using a local variable, you can keep this code at one place and don’t have to smear it across the complete method.