The comparison of the following benchmark results in 0.1 sec vs 0.12 sec on my computer. I first thought the result is strange. I thought __hash__
will be applied to all the fields of the class, therefore, the hashing time should be equal.
However, afterward, I notice that object
class has its own __hash__
function, from the documentation.
I want to know the reason why hashing object is that fast. More specifically, I want to know how the __hash__
function is implemented for the object
class. Is object.__hash__
compute the hash of pointer of the object internally?
import time
string = "hash_test"
class A(object):
def __init__(self, string):
self.a = (string, string, string, string)
a = A(string)
ts = time.time()
for i in range(1000000):
hash(a)
print(time.time() - ts) # 0.1 sec
ts = time.time()
str_tuple = (string, string, string, string)
for i in range(1000000):
hash(str_tuple)
print(time.time() - ts) # 0.12 sec