0
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)

Lelouch Lamperouge
  • 8,171
  • 8
  • 49
  • 60
  • Python's LEGB scoping rule means that always checks the local scope first when looking up the value of a variable. – martineau Oct 30 '14 at 23:37
  • But does it take that much time that initializing a new variable is faster than a global lookup? – Lelouch Lamperouge Oct 31 '14 at 03:27
  • I suppose...although 23 billionths of a second for two variables isn't very much. It's also part of the price one pays for using a dynamic language. You could try making them the default values of a couple of optional function arguments to avoid the overhead of initializing them every time the function is called -- in other words, like pre-initialized local variables. – martineau Oct 31 '14 at 08:47

0 Answers0