Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>Start with</p> <pre><code> NSUInteger prime = 31; NSUInteger result = 1; </code></pre> <p>Then for every primitive you do</p> <pre><code> result = prime * result + var </code></pre> <p>For 64bit you might also want to shift and xor.</p> <pre><code> result = prime * result + (int) (var ^ (var &gt;&gt;&gt; 32)); </code></pre> <p>For objects you use 0 for nil and otherwise their hashcode.</p> <pre><code> result = prime * result + [var hash]; </code></pre> <p>For booleans you use two different values</p> <pre><code> result = prime * result + (var)?1231:1237; </code></pre> <hr> <h2>Explanation and Attribution</h2> <p>This is not tcurdt's work, and comments were asking for more explanation, so I believe an edit for attribution is fair.</p> <p>This algorithm was popularized in the book "Effective Java", and <a href="http://www.scribd.com/doc/36454091/Effective-Java-Chapter3" rel="noreferrer">the relevant chapter can currently be found online here</a>. That book popularized the algorithm, which is now a default in a number of Java applications (including Eclipse). It derived, however, from an even older implementation which is variously attributed to Dan Bernstein or Chris Torek. That older algorithm originally floated around on Usenet, and certain attribution is difficult. For example, there is some <a href="http://svn.apache.org/repos/asf/apr/apr/trunk/tables/apr_hash.c" rel="noreferrer">interesting commentary in this Apache code</a> (search for their names) that references the original source.</p> <p>Bottom line is, this is a very old, simple hashing algorithm. It is not the most performant, and it is not even proven mathematically to be a "good" algorithm. But it is simple, and a lot of people have used it for a long time with good results, so it has a lot of historical support.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload