|
1 | 1 | import copy |
2 | 2 | import pickle |
| 3 | +import timeit |
3 | 4 |
|
4 | 5 | from nameparser import HumanName |
5 | 6 | from nameparser.config import Constants, RegexTupleManager, SetManager, TupleManager |
@@ -350,3 +351,33 @@ def test_replaced_manager_no_longer_invalidates_cache(self) -> None: |
350 | 351 | replaced.add('ghost') |
351 | 352 | self.assertIs(c.suffixes_prefixes_titles, primed) |
352 | 353 | self.assertNotIn('ghost', c.suffixes_prefixes_titles) |
| 354 | + |
| 355 | + |
| 356 | +class SuffixesPrefixesTitlesPerformanceTests(HumanNameTestBase): |
| 357 | + """Guard against accidental cache removal on suffixes_prefixes_titles. |
| 358 | +
|
| 359 | + This library is commonly used to parse large batches of names, so |
| 360 | + suffixes_prefixes_titles must remain cached. Without the cache, each call |
| 361 | + rebuilds the union from ~700 strings (~50-100 µs); with it, repeated access |
| 362 | + is ~1000x faster. This test asserts that 10 000 repeated calls complete |
| 363 | + well within the time a single uncached union build would take. |
| 364 | + """ |
| 365 | + |
| 366 | + def test_repeated_access_is_cached(self) -> None: |
| 367 | + c = Constants() |
| 368 | + first = c.suffixes_prefixes_titles |
| 369 | + second = c.suffixes_prefixes_titles |
| 370 | + assert first is second, "suffixes_prefixes_titles should return the same cached object on repeated access" |
| 371 | + |
| 372 | + n = 10_000 |
| 373 | + elapsed = timeit.timeit(lambda: c.suffixes_prefixes_titles, number=n) |
| 374 | + |
| 375 | + # One uncached union build over ~700 strings takes ~50-100 µs on any |
| 376 | + # modern machine. If caching is broken, 10 000 calls would take |
| 377 | + # seconds; with caching they finish in well under 10 ms total. |
| 378 | + limit = 0.010 # 10 ms = 1 µs/call average |
| 379 | + assert elapsed < limit, ( |
| 380 | + f"suffixes_prefixes_titles appears uncached: {n} calls took " |
| 381 | + f"{elapsed * 1000:.1f} ms (limit {limit * 1000:.0f} ms). " |
| 382 | + "Was _pst caching removed?" |
| 383 | + ) |
0 commit comments