Skip to content

Commit 850084d

Browse files
authored
Add benchmarks for cached properties on slotted classes (#1489)
To have some numbers for #1333.
1 parent c0111e6 commit 850084d

File tree

1 file changed

+42
-0
lines changed

1 file changed

+42
-0
lines changed

bench/test_benchmarks.py

Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,9 @@
44

55
from __future__ import annotations
66

7+
import functools
8+
import time
9+
710
import pytest
811

912
import attrs
@@ -172,3 +175,42 @@ def test_astuple_atomic():
172175

173176
for _ in range(ROUNDS):
174177
at(c)
178+
179+
180+
class TestCachedProperties:
181+
@attrs.define
182+
class Slotted:
183+
x: int = 0
184+
185+
@functools.cached_property
186+
def cached(self):
187+
time.sleep(0.1)
188+
return 42
189+
190+
@attrs.define(slots=False)
191+
class Unslotted:
192+
x: int = 0
193+
194+
@functools.cached_property
195+
def cached(self):
196+
time.sleep(0.1)
197+
return 42
198+
199+
def test_first_access(self):
200+
"""
201+
Benchmark first access to a cached property (computation + storage).
202+
"""
203+
for _ in range(ROUNDS):
204+
c = self.Slotted(42)
205+
_ = c.cached
206+
207+
def test_repeated_access(self):
208+
"""
209+
Benchmark repeated access to a cached property (should use stored
210+
value).
211+
"""
212+
c = self.Slotted(42)
213+
_ = c.cached # Prime the cache
214+
215+
for _ in range(ROUNDS):
216+
_ = c.cached

0 commit comments

Comments
 (0)