c# - Why is an initial prime used in GetHashCode implementations? -


looking @ what best algorithm overridden system.object.gethashcode? struck in many of answers suggest hashcodes of type hash = hash*(prime) + item.gethashcode() value of hash seeded prime rather 0.

i understand reason prime in calculation portion coprime numbers useful in many ways.

what don't understand why hash initialised non-zero number in first place.

looking @ precise example:

int hash = 17; hash = hash * 23 + field1.gethashcode(); hash = hash * 23 + field2.gethashcode(); hash = hash * 23 + field3.gethashcode(); return hash; 

for shorthand lets let field1.gethashcode() represented f1 (and on others) , initial hash value gives:

int hash = i; hash = * 23 + f1; hash = (i * 23 + f1)* 23 + f2; hash = ((i * 23 + f1)* 23 + f2)* 23 + f3; 

expanding brackets in last row:

hash = (i*23*23 + f1*23 + f2)* 23 + f3; hash = i*23*23*23 + f1*23*23 + f2*23 + f3; 

so can see effect of initial hash value increase final has value constant value of i*23*23*23 generalise i*23^(number of fields).

so how help? in event of f1, f2, f3 being 0 problem if final hash 0? better non-zero? thought implementations of things dictionaries or hash sets use hash value prefer non-zero values reason can't think reason might be. or other things of course these things little bit arcane people use tried , tested thing , initial value gets propagated though there no reason it.

i tried looking microsoft hashcodes ones found used external code calculate them (object, string) or special (the implementation of gethashcode on anonymous objects seeds hashcode based off of property names of anonymous objects different because isn't constant initial value).

so in summary why initial constant value in hash code implementations?

edit: why use prime number in hashcode? suggested duplicate , site wants me edit question explain why not duplicate... have acknowledged primes used multiplier in calculations , understand why is. question explicitly use initial seed in hash code algorithm. suggested duplicate doesn't explicitly prime used answers address use of multiplying factor not relevant question.

this question has some answers on computer science se. in short: initial constant adapted hashes take variable number of inputs, , you’re right doesn’t matter in example.


Comments

Popular posts from this blog

Is there a better way to structure post methods in Class Based Views -

performance - Why is XCHG reg, reg a 3 micro-op instruction on modern Intel architectures? -

jquery - Responsive Navbar with Sub Navbar -