Inefficient use of ContainsKey — CodeQL query help documentation
CodeQL query help documentation » CodeQL query help for C# » Inefficient use of ContainsKey ¶ ID: cs/inefficient-containskey Kind: problem Security severity: Severity: recommendation Precision: high Tags: - quality - reliability - performance Query suites: - csharp-code-quality.qls - csharp-security-and-quality.qls Click to see the query in the CodeQL repository Using the ContainsKey method to check whether a dictionary contains a value before getting the value is inefficient because it performs two operations on the dictionary.
It is simpler and more efficient to combine the operations using the TryGetValue method. Recommendation ¶ Replace the two operations with a single call to TryGetValue . Example ¶ This code first checks whether ip is in the hostnames table, before looking up the value. // BAD: Two operations on the hostnames table. if ( hostnames . ContainsKey ( ip )) return hostnames [ ip ]; This code performs the same function as the example above, but uses TryGetValue , which makes it is more efficient. // GOOD: One operation on the hostnames table. if ( hostnames .
TryGetValue ( ip , out hostname )) return hostname ; References ¶ MSDN: ContainsKey Method , TryGetValue Method . © GitHub, Inc. Terms Privacy