From 16ccb2a42d16c1c27784732178881c968b3e8d1f Mon Sep 17 00:00:00 2001 From: Kunjan Aggarwal Date: Fri, 10 Jun 2022 23:01:49 -0700 Subject: [PATCH] Remove redundant map lookups in `commitToMemory` 1. Instead of `HashMap.contains` check before `HashMap.remove`, directly perform `HashMap.remove`. - When _key_ is not present there is no impact as exactly same code gets executed inside implementation of `HashMap.contains` and `HashMap.remove` for this case. - When _key_ is present we save one wasteful hash lookup that would have happened due to `HashMap.contains`. 1. Instead of `HashMap.contains` check before `HashMap.get`, directly perform `HashMap.get`. - When _key_ is not present there is no impact as exactly same `getNode` method gets invoked in both `HashMap.contains` and `HashMap.remove` implementations. - When _key_ is present we same one wasteful hash lookup that would have happened due to `HashMap.contains`. - Also we save on a null check by reversing the _equals_ check as we know new value to be added to map is not _null_. --- core/java/android/app/SharedPreferencesImpl.java | 12 +++++------- 1 file changed, 5 insertions(+), 7 deletions(-) diff --git a/core/java/android/app/SharedPreferencesImpl.java b/core/java/android/app/SharedPreferencesImpl.java index 1ebf56550e03d..6d3cb0ee24135 100644 --- a/core/java/android/app/SharedPreferencesImpl.java +++ b/core/java/android/app/SharedPreferencesImpl.java @@ -558,16 +558,14 @@ private MemoryCommitResult commitToMemory() { // setting a value to "null" for a given key is specified to be // equivalent to calling remove on that key. if (v == this || v == null) { - if (!mapToWriteToDisk.containsKey(k)) { + if (mapToWriteToDisk.remove(k) == null) { + //mapToWriteToDisk does not contain given key, k continue; } - mapToWriteToDisk.remove(k); } else { - if (mapToWriteToDisk.containsKey(k)) { - Object existingValue = mapToWriteToDisk.get(k); - if (existingValue != null && existingValue.equals(v)) { - continue; - } + if (v.equals(mapToWriteToDisk.get(k))) { + //mapToWriteToDisk already contains the same key value pairing + continue; } mapToWriteToDisk.put(k, v); }