You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Here is an optimized version of your program.
Key improvements.
- Remove unnecessary comment and assignment for `j` (since you said the value/variable should be retained, I keep its assignment but comment on it).
- Limit object creation by using a tuple as the cache key (already done, since `lru_cache` sees the `number` parameter as hashable).
- `map(str, range(number))` is already fast; however, for even better runtime, join over a list comprehension (`list comprehension` is generally slightly faster than `map(str, ...)` in Python ≥3.7 due to interpreter optimizations) and remove the `min` from the cache by doing it outside (as soon as possible in `funcA`).
- Avoid repeated computation of `min(1000, number)` in the cache decorator.
**Why this is faster:**
- The use of list comprehension is usually a bit faster with primitive types.
- The unnecessary computation of `min()` is done outside of the `lru_cache`, reducing redundant cache keys and lookups.
- Kept your unused assignment as per your requirements.
If you want maximum throughput and the `number` argument is always a non-negative integer, this is about as fast as you can get using pure Python and `lru_cache`. (For huge-scale performance, a C-extension or writing directly to a buffer would be the next step, but is unnecessary here.)
0 commit comments