# Fast hamming distance function in Julia that returns a distance matrix

**URL:** <https://discourse.julialang.org/t/fast-hamming-distance-function-in-julia-that-returns-a-distance-matrix/55716>\
**Category:** Performance\
**Tags:** question, distances\
**Created:** [February 21, 2021, 1:34pm UTC](https://discourse.julialang.org/t/fast-hamming-distance-function-in-julia-that-returns-a-distance-matrix/55716 "2021-02-21T13:34:02Z")\
**Posts on this page:** 1\
**Showing post:** 12

<div class="post-metadata">

**Author:** ![lungben](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/lungben/32/12314_2.png) [@lungben](https://discourse.julialang.org/u/lungben)\
**Post date:** [February 21, 2021, 6:13pm UTC](https://discourse.julialang.org/t/fast-hamming-distance-function-in-julia-that-returns-a-distance-matrix/55716/12 "2021-02-21T18:13:46Z")

</div>

I do not know if this is the most efficient way for matrices, but for pair-wise Hamming distance this way was the fastest I could find:

> [@Optimization: How to make sure XOR is performed in chunks](https://discourse.julialang.org/t/optimization-how-to-make-sure-xor-is-performed-in-chunks/33947/32):
>
> A bit late to the party, but I just had a similar use case today. The fastest method I could find was working on UInt8 instead of BitArrays, count\_ones and LoopVectorization: function hamming\_distance(h1, h2) s = 0 @avx for i = 1:length(h1) s += count\_ones(xor(h1[i], h2[i])) end s end h1 = Vector{UInt8}(randstring(hash\_length)) h2 = Vector{UInt8}(randstring(hash\_length)) julia\> @btime hamming\_distance($h1, $h2) 11.813 ns (0 allocations: 0 bytes) The method above (b…

---

_[View the full topic](https://discourse.julialang.org/t/fast-hamming-distance-function-in-julia-that-returns-a-distance-matrix/55716)._
