I noticed that creating instances of attr objects was expensive:
# python >= 3.3, rough timing
import time
from attr import attributes, attr
from attr.validators import instance_of
@attributes
class Arch(object):
name = attr("name")
@attributes
class ValidatedArch(object):
name = attr("name", validator=instance_of(str))
def build_platform():
return Arch("x86")
def timeit(func):
times = []
for i in range(10000):
start = time.perf_counter()
func()
times.append(time.perf_counter() - start)
return "Min cost across 10000 iterations: {:.2f} us".format(min(times) * 1e6)
print(timeit(lambda: Arch("x86")))
print(timeit(lambda: ValidatedArch("x86")))
I see a factor of ~ 50x (0.8us vs 34 us) on my machine. A quick profiling shows that almost all the difference comes from the deepcopy in the attr._make.fields function.
For non trivial classes with a few attributes, the construction cost quickly reaches the hundreds of us.
I noticed that creating instances of attr objects was expensive:
I see a factor of ~ 50x (0.8us vs 34 us) on my machine. A quick profiling shows that almost all the difference comes from the deepcopy in the
attr._make.fieldsfunction.For non trivial classes with a few attributes, the construction cost quickly reaches the hundreds of us.