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

Performance of HashMap.update is slow #48866

Closed
gaaclarke opened this issue Apr 22, 2022 · 1 comment
Closed

Performance of HashMap.update is slow #48866

gaaclarke opened this issue Apr 22, 2022 · 1 comment
Labels
area-vm Use area-vm for VM related issues, including code coverage, and the AOT and JIT backends.

Comments

@gaaclarke
Copy link
Contributor

This tracker is for issues related to:

  • Dart core libraries ("dart:async", "dart:io", etc.)

Map.update is implemented as:

  V update(K key, V update(V value), {V Function()? ifAbsent}) {
    if (this.containsKey(key)) {
      return this[key] = update(this[key] as V);
    }
    if (ifAbsent != null) {
      return this[key] = ifAbsent();
    }
    throw ArgumentError.value(key, "key", "Key not in map.");
  }

This performs 3 lookups into the map. The map implementations should override their update implementations to be faster:

class HashMap<K, V> {
  @override
  V update(K key, V update(V value), {V Function()? ifAbsent}) {
    final hashCode = key.hashCode;
    final buckets = _buckets;
    final length = buckets.length;
    final index = hashCode & (length - 1);
    var entry = buckets[index];
    while (entry != null) {
      if (hashCode == entry.hashCode && entry.key == key) {
        entry.value = update(value);
        return;
      }
      entry = entry.next;
    }
    if (ifAbsent != null) {
      _addEntry(buckets, index, length, key, ifAbsent(), hashCode);
    }
    throw ArgumentError.value(key, "key", "Key not in map.");
  }
}

In local benchmarks the current HashMap.update implementation is ~2x slower than just using x[y] = x[y] + 1. In SplayTreeMap it's ~40% faster to use update because it does update in one pass.

@gaaclarke
Copy link
Contributor Author

@lrhn lrhn added the area-vm Use area-vm for VM related issues, including code coverage, and the AOT and JIT backends. label Apr 23, 2022
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
area-vm Use area-vm for VM related issues, including code coverage, and the AOT and JIT backends.
Projects
None yet
Development

No branches or pull requests

2 participants