Sobes.tech
Middle

What properties should a good hash function have?

sobes.tech AI

Answer from AI

A good hash function should possess the following properties:

  • Determinism: for the same input value, it should always return the same hash.
  • Uniform distribution: minimize collisions by evenly distributing values across the hash space.
  • Speed: compute quickly so as not to slow down the program.
  • Collision resistance: different input data should, with high probability, produce different hashes.
  • Minimal sensitivity to similar inputs: small changes in input should lead to significant changes in the hash (avalanche effect).

Example in Go for computing a string hash using the built-in hash/fnv package:

import (
    "fmt"
    "hash/fnv"
)

func hash(s string) uint32 {
    h := fnv.New32a()
    h.Write([]byte(s))
    return h.Sum32()
}

func main() {
    fmt.Println(hash("example"))
}