Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Use values iterator and update in map equality/hash #718

Merged
merged 4 commits into from
Nov 6, 2024
Merged
Show file tree
Hide file tree
Changes from 3 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions pkgs/collection/CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,6 +1,9 @@
## 1.19.1-wip

- Add `IterableMapEntryExtension` for working on `Map` as a list of pairs, using
`Map.entries`.
- Optimize equality and hash code for maps by using `update` and a `values`
iterator to avoid extra lookups.

## 1.19.1

Expand Down
21 changes: 13 additions & 8 deletions pkgs/collection/lib/src/equality.dart
Original file line number Diff line number Diff line change
Expand Up @@ -325,16 +325,19 @@ class MapEquality<K, V> implements Equality<Map<K, V>> {
var length = map1.length;
if (length != map2.length) return false;
Map<_MapEntry, int> equalElementCounts = HashMap();
var values1 = map1.values.iterator;
for (var key in map1.keys) {
var entry = _MapEntry(this, key, map1[key]);
var count = equalElementCounts[entry] ?? 0;
equalElementCounts[entry] = count + 1;
var value = (values1..moveNext()).current;
var entry = _MapEntry(this, key, value);
equalElementCounts.update(entry, (i) => i + 1, ifAbsent: () => 1);
jakemac53 marked this conversation as resolved.
Show resolved Hide resolved
}
final values2 = map2.values.iterator;
for (var key in map2.keys) {
var entry = _MapEntry(this, key, map2[key]);
var count = equalElementCounts[entry];
if (count == null || count == 0) return false;
equalElementCounts[entry] = count - 1;
var value = (values2..moveNext()).current;
var entry = _MapEntry(this, key, value);
var count =
equalElementCounts.update(entry, (i) => i - 1, ifAbsent: () => -1);
jakemac53 marked this conversation as resolved.
Show resolved Hide resolved
if (count < 0) return false;
}
return true;
}
Expand All @@ -343,9 +346,11 @@ class MapEquality<K, V> implements Equality<Map<K, V>> {
int hash(Map<K, V>? map) {
if (map == null) return null.hashCode;
var hash = 0;
var values = map.values.iterator;
for (var key in map.keys) {
var value = (values..moveNext()).current;
var keyHash = _keyEquality.hash(key);
var valueHash = _valueEquality.hash(map[key] as V);
var valueHash = _valueEquality.hash(value);
hash = (hash + 3 * keyHash + 7 * valueHash) & _hashMask;
}
hash = (hash + (hash << 3)) & _hashMask;
Expand Down