Why is creating a class in Python so much slower than instantiating a class?

前端 未结 4 1241
谎友^
谎友^ 2021-01-31 17:33

I found that creation of a class is way slower than instantiation of a class.

>>> from timeit import Timer as T
>>> def calc(n):
...     return         


        
4条回答
  •  长发绾君心
    2021-01-31 17:54

    A quick dis of the following functions:

    def a():
        class Haha(object):
             pass
    
    
    
    def b():
        Haha()
    

    gives:

    2           0 LOAD_CONST               1 ('Haha')
                3 LOAD_GLOBAL              0 (object)
                6 BUILD_TUPLE              1
                9 LOAD_CONST               2 (", line 2>)
                12 MAKE_FUNCTION            0
                15 CALL_FUNCTION            0
                18 BUILD_CLASS         
                19 STORE_FAST               0 (Haha)
                22 LOAD_CONST               0 (None)
                25 RETURN_VALUE        
    

    and

    2           0 LOAD_GLOBAL              0 (Haha)
                3 CALL_FUNCTION            0
                6 POP_TOP             
                7 LOAD_CONST               0 (None)
                10 RETURN_VALUE        
    

    accordingly.

    By the looks of it, it simply does more stuff when creating a class. It has to initialize class, add it to dicts, and wherever else, while in case of Haha() is just calls a function.

    As you noticed doing garbage collection when it gets's too slow speeds stuff up again, so Marcin's right in saying that it's probably memory fragmentation issue.

提交回复
热议问题