1
votes

I'm writing a disk cache where filenames are the keys. The keys can be longer than the max filename length, so they need to be hashed. What are some fast hash functions with extremely low probability of collisions (so that I can ignore it)?

Basically, I'm looking for a faster alternative to MD5 with no security requirenments.

(Platform = Android, language = Java.)

2
1) Why must it be fast? 2) you cannot ignore collisions. 3) birthday paradox - wildplasser
Which programming language are you using?Doesn't it has a hash table? Do you think there is a problem using its hash function to use the filename as the key? - Cratylus
@wildplasser 1) faster is better 2) I can if they're very unlikely - fhucho
@wildplasser 32bit hash still has non-ignorable possibility of a collision. My cache currently uses MD5 and assumes that collisions never happen. So I'm basically looking for faster and not-necessarily-secure MD5. - fhucho
xxHash has an internal state of 128 bits, which is the same size as MD5. It currently merge them to create a final 32-bits hash, but it's not difficult to change the final step to create 64-bits hashes, or 128-bits hashes. 128-bits is probably what you are looking for : negligible enough probability of collision, even with several billions files. - Cyan

2 Answers

6
votes

if your hash is uniformly distributed then you can calculate the size of the hash (in bits) that you need from the approx number of files you expect to handle before a collision. basically, because of the birthday paradox, it's twice the number of bits.

so, for example, if you are happy with a collision after a million files then you need a has that is about 40 bits log (2 * log2(1e6)).

conversely, if a hash is N bits, then it's good for 2^(N/2) files without collision (more or less).

there are many fast hashes. for example, xxhash is a 64 bit hash, so is good for about 4,000,000,000 files. google's fast-hash is another.

if you want more than 64bits (more than ~4 billion files before a collision) then you can either use a hash with a larger output or join two 64bit hashes together (one hash from the original file and one with it modified in some way (eg prefixed with a space)).