So I have a list of strings that I need to instantiate once every time a service is called. Is it worth it to convert the List<String>
to a HashSet<String>
and then check if the String is in the hashSet?
eg.
HashSet<String> services = new HashSet<String>((List<String>) services);
I know checking for the string in the list is O(n) and the check for the string in the hashSet is O(1). I think the conversion is probably O(n).
Is there a performance benefit to the recast if I am not searching over the list more than a few times?
There is no benefit to switching. Your Bio O performance analysis is correct.
List
and Set
are not the same thing:
So the first questions you need to ask yourself are:
If the answer to both questions is no it is better to use an HashSet instead of the List. This will guarantee better performances retrieving elements.
If you can't change the List to an HashSet but you need to duplicate data structures it is necessary to check better your code to see if the set creation time is slower than the time gained for retrieving elements
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With