In [8]: %paste
PRIME = 16777619
UINT32_MAX = 4294967295 # (2 ** 32) - 1
def fnv1a_32_global(string):
hashval = 2166136261
for character in string:
hashval ^= ord(character)
hashval = (hashval * PRIME) & UINT32_MAX
return hashval
In [9]: %timeit fnv1a_32_global(mystr)
1000000 loops, best of 3: 990 ns per loop
In [6]: %paste
def fnv1a_32_local(string):
hashval = 2166136261
PRIME = 16777619
UINT32_MAX = 4294967295 # (2 ** 32) - 1
for character in string:
hashval ^= ord(character)
hashval = (hashval * PRIME) & UINT32_MAX
return hashval
In [7]: %timeit fnv1a_32_local(mystr)
1000000 loops, best of 3: 967 ns per loop
I am trying to confirm (and understand why) initializing a local var on every function call and accessing it is faster than once initializing a global var and accessing it.
This result is consistent across several test attempts.
Additinal question: can this code be made even faster (I tried using a c-library pyfasthash. It is even slower than the above implementations)