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 T("class Haha(object): pass").timeit(n)
<<After several these 'calc' things, at least one of them have a big number, eg. 100000>>
>>> calc(9000)
15.947055101394653
>>> calc(9000)
17.39099097251892
>>> calc(9000)
18.824054956436157
>>> calc(9000)
20.33335590362549
Yeah, create 9000 classes took 16 secs, and becomes even slower in the subsequent calls.
And this:
>>> T("type('Haha', b, d)", "b = (object, ); d = {}").timeit(9000)
gives similar results.
But instantiation don't suffer:
>>> T("Haha()", "class Haha(object): pass").timeit(5000000)
0.8786070346832275
5000000 instances in less than one sec.
What makes the creation this expensive?
And why the creation process become slower?
EDIT:
How to reproduce:
start a fresh python process, the initial several "calc(10000)"s give a number of 0.5 on my machine. And try some bigger values, calc(100000), it can't end in even 10secs, interrupt it, and calc(10000), gives a 15sec.
EDIT:
Additional fact:
If you gc.collect() after 'calc' becomes slow, you can get the 'normal' speed at beginning, but the timing will increasing in subsequent calls
>>> from a import calc
>>> calc(10000)
0.4673938751220703
>>> calc(10000)
0.4300072193145752
>>> calc(10000)
0.4270968437194824
>>> calc(10000)
0.42754602432250977
>>> calc(10000)
0.4344758987426758
>>> calc(100000)
^CTraceback (most recent call last):
File "<stdin>", line 1, in <module>
File "a.py", line 3, in calc
return T("class Haha(object): pass").t