diff --git a/client/src/com/aerospike/client/lua/LuaMap.java b/client/src/com/aerospike/client/lua/LuaMap.java index 0d9ed0cad..263b05d67 100644 --- a/client/src/com/aerospike/client/lua/LuaMap.java +++ b/client/src/com/aerospike/client/lua/LuaMap.java @@ -99,17 +99,26 @@ public LuaMap merge(LuaMap map2, LuaFunction func) { } public LuaMap diff(LuaMap map2) { - HashMap target = new HashMap(map.size() + map2.map.size()); - - for (Entry entry : map.entrySet()) { - if (!map2.map.containsKey(entry.getKey())) { - target.put(entry.getKey(), entry.getValue()); + // Cache reference to other map to avoid repeated field access + final Map other = map2.map; + + // Expected number of entries in the result is at most sum of sizes. + // Compute initial capacity to avoid rehashing (load factor = 0.75). + int expected = map.size() + other.size(); + int capacity = (int)(expected / 0.75f) + 1; + HashMap target = new HashMap(capacity); + + // Copy all entries from this map, then process the other map: + // - If a key exists in target (was in this map), remove it (present in both -> exclude). + // - Otherwise, add the entry from the other map (unique to other). + target.putAll(map); + for (Entry entry : other.entrySet()) { + LuaValue key = entry.getKey(); + if (target.containsKey(key)) { + target.remove(key); } - } - - for (Entry entry : map2.map.entrySet()) { - if (!map.containsKey(entry.getKey())) { - target.put(entry.getKey(), entry.getValue()); + else { + target.put(key, entry.getValue()); } } return new LuaMap(instance, target);