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

前端 未结 4 1240
谎友^
谎友^ 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:55

    It isn't: Only your contrived tests show slow class creation. In fact, as @Veedrac shows in his answer, this result is an artifact of timeit disabling garbage collection.

    Downvoters: Show me a non-contrived example where class creation is slow.

    In any case, your timings are affected by the load on your system at the time. They are really only useful for comparisons performed at pretty much the same time. I get about 0.5s for 9000 class creations. In fact, it's about 0.3s on ideone, even when performed repeatedly: http://ideone.com/Du859. There isn't even an upward trend.

    So, in summary, it is much slower on your computer than others, and there is no upwards trend on other computers for repeated tests (as per your original claim). Testing massive numbers of instantiations does show slowing down, presumably because the process consumes a lot of memory. You have shown that allocating a huge amount of memory slows a process down. Well done.

    That ideone code in full:

    from timeit import Timer as T
    def calc(n):
    return T("class Haha(object): pass").timeit(n)
    
    for i in xrange(30):
    print calc(9000)
    

提交回复
热议问题