简体   繁体   中英

Using Hash in C#

I have lots of objects. I should evaluate one of thier members.them one by one. The first is evaluating them one by one --------> pseudo code

while (anyObjectExists)
{
      Class1 obj = getObject();
      double evalNum = eval(obj.member1);
}

but eval is a time consuming method. and lots of objects have same member1. member1 is an array of type sbyte. So I tried to ind another way. That was my way: ------->pseudo code

HashTable evaluatedObject = new HashTable();
while(anyObjectExists)
{
      Class1 obj = getObject();
      if (evaluatedObjects.Contain(obj))
      {
            double evalNum = evaluatedObjects[obj];
      }
      else
      {
            double evalNum = eval(obj.member1);
            evaluatedObjects.Add(obj, evalNum);
      }
}

I knew that I should override getHashCode and Equals method for sbyte. As you can see the eval method only uses member1 from Class1. So I added to methods to my Class1 in this way

    public override int GetHashCode()
    {
        return 1;
    } 
    public override bool Equals(Object compareState)
    {
        if (!this.member1.SequenceEqual(((Class1)compareState).member1))
            return false;
        return true;
    }

Ok. I thought it is done. But when I run my program ... it is a god damn slow program. It is a lot slower than the first program. I tested it. It can find added objects. There is nothing wrong about it. But it is very very slow. I though hash can retrieve data in 1 or 2 shot. What did I wrong?

Any help would be highly welcomed.

You should return a valid hash code, like this.member1.Count().GetHashCode() not 1 , in your case it always compare them by their hash and because they are a same compare them by their equal, and your function runs slower.

Edit: Also I think your eval function is faster than your work on sequence equals. in fact your (Class1)compareState is time consuming and also your sequence comparison is time consuming too.

Do not fix the HashCode to 1, because it will make necessary for the data structures that relies on hashing to handle a bunch of collisions. In this case there will be no difference between using a hash table or a linked list. When searching for an object (by calling the Cointains method, for instance), it will be necessary to evaluate each object in your collection, complexity O(N), instead of accessing the object by its hash code, complexity O(1).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM