ContainsKey 的低效使用¶
ID: cs/inefficient-containskey
Kind: problem
Security severity:
Severity: recommendation
Precision: high
Tags:
- maintainability
- efficiency
Query suites:
- csharp-security-and-quality.qls
使用 ContainsKey
方法在获取值之前检查字典是否包含某个值效率低下,因为它会在字典上执行两次操作。使用 TryGetValue
方法组合操作更简单、更高效。
建议¶
将这两个操作替换为对 TryGetValue
的单个调用。
示例¶
此代码首先检查 hostnames
表中是否存在 ip
,然后再查找该值。
// BAD: Two operations on the hostnames table.
if(hostnames.ContainsKey(ip))
return hostnames[ip];
此代码执行与上述示例相同的功能,但使用 TryGetValue
,因此效率更高。
// GOOD: One operation on the hostnames table.
if(hostnames.TryGetValue(ip, out hostname))
return hostname;
参考¶
MSDN:ContainsKey 方法、TryGetValue 方法。