1

The following example is based on the hughdbrown Dictionary vs Object - which is more efficient and why?

import time

ITER_COUNT = 5_000_000

def timeit(method):
    def timed(*args, **kw):
        s = time.time()
        result = method(*args, **kw)
        e = time.time()
        print(f'{method.__name__} uses {e-s:.2f} seconds')
        return result
    return timed

class SlotObject:
    __slots__ = ['attribute']

    def __init__(self):
        self.attribute = 0

@timeit
def append_slot_to_dict():
    append_dict = {}
    for i in range(ITER_COUNT):
        one_slot_obj = SlotObject()
        one_slot_obj.attribute = 100
        append_dict[i] = one_slot_obj
    return append_dict

@timeit
def append_dict_to_dict():
    append_dict = {}
    for i in range(ITER_COUNT):
        one_dict_obj = {}
        one_dict_obj['attribute'] = 100
        append_dict[i] = one_dict_obj
    return append_dict

if __name__ == '__main__':
    for i in range(10):
        print(f"\n =========== Test =========== ")
        append_slot_to_dict()
        append_dict_to_dict()

 =========== Test ===========
append_slot_to_dict uses 2.77 seconds
append_dict_to_dict uses 1.12 seconds

 =========== Test ===========
append_slot_to_dict uses 2.74 seconds
append_dict_to_dict uses 1.12 seconds

 =========== Test ===========
append_slot_to_dict uses 2.71 seconds
append_dict_to_dict uses 1.12 seconds

 =========== Test ===========
append_slot_to_dict uses 2.73 seconds
append_dict_to_dict uses 1.12 seconds

 =========== Test ===========
append_slot_to_dict uses 2.67 seconds
append_dict_to_dict uses 1.12 seconds

 =========== Test ===========
append_slot_to_dict uses 2.55 seconds
append_dict_to_dict uses 1.12 seconds

 =========== Test ===========
append_slot_to_dict uses 2.89 seconds
append_dict_to_dict uses 1.12 seconds

 =========== Test ===========
append_slot_to_dict uses 2.66 seconds
append_dict_to_dict uses 1.12 seconds

 =========== Test ===========
append_slot_to_dict uses 2.69 seconds
append_dict_to_dict uses 1.12 seconds

 =========== Test ===========
append_slot_to_dict uses 2.64 seconds
append_dict_to_dict uses 1.12 seconds

Question> Can someone tell me why my SlotObject insertion is significantly slower than dict-dict insertion?

Thank you

q0987
  • 34,938
  • 69
  • 242
  • 387

0 Answers0