Dart xoring two hashcodes are always going to return a new unique hashcode?

I am writing a class that needs to have a unique hash code based on two of its fields, and I would like to know if XHOR 2 hash codes are enough to generate a unique and consistent hash code for my object?

class _TypeMatch{
  final Type _potentialSubtype;
  final Type _supertype;

  int _cachedHashCode;  

  _TypeMatch(this._potentialSubtype, this._supertype){
    _cachedHashCode = _potentialSubtype.hashCode ^ _supertype.hashCode;
  }

  int get hashCode => _cachedHashCode;

  bool operator ==(other){
    return other is _TypeMatch && _cachedHashCode == other._cachedHashCode;
  }
}

      

I saw this question here which seems to suggest that XORing the other two hashcodes is the right thing to do, but they flush each hashcode multiple times by 2 large primes and I was not sure why or if it was necessary ... I am primarily concerned that for two types A and B:

new _TypeMatch(A, B) == new _TypeMatch(A, B) // is true for all A and B

      

and that the computation of the combined hash is as efficient as possible, since creating a new _TypeMatch will be a major part of the system and therefore any performance inefficiencies will be felt radically throughout the system.

Update

Hashcodes are used, for example, in a hash map or hash table to evenly distribute stored key / values ​​into "slots". A single slot can contain many keys / values, but with the help of a hash code, it is easy and quick to find the slot in the map and from there look for a specific key / value in a much smaller set of values. This improves speed when searching the map very quickly, no matter what type of data is used for the key. When the hashcode changes for the stored key / value, the value can no longer be retrieved by the key. You can just use1

like hashcode for each object, but it can mess with performance. You get the opposite effect (optimal performance) with a good distribution (different hash codes for different objects), but there is a limit. When you use, for example, a 32-bit integer type for a hash code, the number of hash codes possible is limited. See http://en.wikipedia.org/wiki/Hash_table for details . However, there are many uses for hashes.

+3


source to share


1 answer


I suggest using a method hash2

from the quiver package

https://github.com/google/quiver-dart/blob/master/lib/src/core/hash.dart#L26

You can use it like



import 'package:quiver/core.dart' show hash2;

@override
int get hashCode => hash2(val1, val2);

      

They use this code to combine hash codes

int _combine(int hash, int value) {
  hash = 0x1fffffff & (hash + value);
  hash = 0x1fffffff & (hash + ((0x0007ffff & hash) << 10));
  return hash ^ (hash >> 6);
}

      

+2


source







All Articles