diff --git a/infer/documentation/issues/INEFFICIENT_KEYSET_ITERATOR.md b/infer/documentation/issues/INEFFICIENT_KEYSET_ITERATOR.md new file mode 100644 index 000000000..2355604a0 --- /dev/null +++ b/infer/documentation/issues/INEFFICIENT_KEYSET_ITERATOR.md @@ -0,0 +1,26 @@ +This issue is raised when +- iterating over a HashMap with `ketSet()` iterator +- looking up the key each time + +Instead, it is more efficient to iterate over the loop with `entrySet` which returns key-vaue pairs and gets rid of the hashMap lookup. + For instance, we would raise an issue for the following program: + +```java +void inefficient_loop_bad(HashMap testMap) { + for (String key : testMap.keySet()) { + Integer value = testMap.get(key); // extra look-up cost + foo(key, value); + } +} +``` + +Instead, it is more efficient to have: +```java +void efficient_loop_ok(HashMap testMap) { + for (Map.Entry entry : testMap.entrySet()) { + String key = entry.getKey(); + Integer value = entry.getValue(); + foo(key, value); + } +} +``` diff --git a/infer/src/base/IssueType.ml b/infer/src/base/IssueType.ml index b234823cb..5c8a52c0c 100644 --- a/infer/src/base/IssueType.ml +++ b/infer/src/base/IssueType.ml @@ -633,6 +633,7 @@ let impure_function = register_from_string ~id:"IMPURE_FUNCTION" Error Impurity let inefficient_keyset_iterator = register_from_string ~id:"INEFFICIENT_KEYSET_ITERATOR" Error InefficientKeysetIterator + ~user_documentation:[%blob "../../documentation/issues/INEFFICIENT_KEYSET_ITERATOR.md"] let inferbo_alloc_is_big =