Inefficient use of ContainsKey¶
ID: cs/inefficient-containskey Kind: problem Severity: recommendation Precision: high Tags: - maintainability - efficiency Query suites: - csharp-security-and-quality.qls
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
Replace the two operations with a single call to
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;