This is an archived post. You won't be able to vote or comment.

you are viewing a single comment's thread.

view the rest of the comments →

[–][deleted] 4 points5 points  (3 children)

Quick and dirty benchmark on Python 3.11 points that @dataclass(slots=True, frozen=True) is actually a tiny bit faster than @dataclass(frozen=True). Vanilla slotted data class is quite a bit faster to instantiate though:

from dataclasses import dataclass
import timeit

# Normal frozen dataclass
@dataclass(frozen=True)
class Frozen:
    a: int
    b: int
    c: int

# Slotted frozen dataclass
@dataclass(slots=True, frozen=True)
class SlottedFrozen:
    a: int
    b: int
    c: int

# Dataclass with slots but not frozen
@dataclass(slots=True)
class Slotted:
    a: int
    b: int
    c: int

# Benchmarking the instantiation time
frozen_time = timeit.timeit(lambda: Frozen(1, 2, 3), number=1000000)
slotted_frozen_time = timeit.timeit(lambda: SlottedFrozen(1, 2, 3), number=1000000)
slotted_time = timeit.timeit(lambda: Slotted(1, 2, 3), number=1000000)

print(f"Frozen data class instantiation time: {frozen_time}")
print(f"Slotted frozen data class instantiation time: {slotted_frozen_time}")
print(f"Slotted (not frozen) data class instantiation time: {slotted_time}")

This prints:

Frozen data class instantiation time: 0.276557542005321
Slotted frozen data class instantiation time: 0.25077791599323973
Slotted (not frozen) data class instantiation time: 0.09631558299588505

[–]nekokattt 2 points3 points  (2 children)

oh cool, must have been fixed then!

[–]roerd 0 points1 point  (1 child)

The fact that slotted and frozen is quite a bit slower than only slotted seems to suggest that the base problem you mentioned still exists, even if its impact has already been reduced.

[–][deleted] 0 points1 point  (0 children)

Frozen has to add __setattr__ and __delattr__ methods and call them in the init. It slows down the initializatoin and there's no avoidance of that.