Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there difference in speed between Dictionary.ContainsKey/Value and a foreach loop that checks for a certain key/value

Is there difference in speed between Dictionary.ContainsKey/Value and a foreach loop that checks for a certain key/value?

like image 973
Omu Avatar asked Dec 14 '22 00:12

Omu


2 Answers

ContainsKey is faster :

This method approaches an O(1) operation.

ContainsValue is like a foreach loop.

This method performs a linear search; therefore, the average execution time is proportional to Count. That is, this method is an O(n) operation, where n is Count.

like image 52
Guillaume Avatar answered Feb 14 '23 19:02

Guillaume


Yes.

ContainsKey is nearly O(1). As for ContainsValue, I can't tell for sure, but I think there won't be much difference to a loop.

like image 30
Maximilian Mayerl Avatar answered Feb 14 '23 19:02

Maximilian Mayerl