Skip to content

Commit

Permalink
Optimize murmurHash so that backend C compiler remove runtime check code
Browse files Browse the repository at this point in the history
  • Loading branch information
demotomohiro committed Jun 12, 2024
1 parent 0b5a938 commit 71ac58b
Showing 1 changed file with 11 additions and 3 deletions.
14 changes: 11 additions & 3 deletions lib/pure/hashes.nim
Original file line number Diff line number Diff line change
Expand Up @@ -304,17 +304,25 @@ proc rotl32(x: uint32, r: int): uint32 {.inline.} =
(x shl r) or (x shr (32 - r))

proc murmurHash(x: openArray[byte]): Hash =
# x.len is always 0 or larger.
# But backend C compiler doesn't know that and need to care about
# negative x.len.
# That prevents some optimization.
# This branch tells C compiler that x.len is never negative after
# the branch.
if x.len < 0:
return

# https://github.com/PeterScott/murmur3/blob/master/murmur3.c
const
c1 = 0xcc9e2d51'u32
c2 = 0x1b873593'u32
n1 = 0xe6546b64'u32
m1 = 0x85ebca6b'u32
m2 = 0xc2b2ae35'u32
stepSize = 4 # 32-bit
let
size = len(x)
stepSize = 4 # 32-bit
n = size div stepSize
var
h1: uint32
i = 0
Expand All @@ -327,7 +335,7 @@ proc murmurHash(x: openArray[byte]): Hash =
k1 = (k1 shl 8) or (ord(x[i+j])).uint32

# body
while i < n * stepSize:
while i < size - (stepSize - 1):
var k1: uint32

when nimvm:
Expand Down

0 comments on commit 71ac58b

Please sign in to comment.