⚡️ Speed up function _cached_joined by 8%
#417
Closed
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
📄 8% (0.08x) speedup for
_cached_joinedincode_to_optimize/code_directories/simple_tracer_e2e/workload.py⏱️ Runtime :
112 milliseconds→104 milliseconds(best of42runs)📝 Explanation and details
Here’s an optimized version of your program.
Key improvements:
map(str, range(number))with a list comprehension and use" ".join(str(i) for i in range(number)). In CPython 3.11, both are close in speed, but since you want maximum speed and minimal memory per call, it actually pays off to use a preallocated list of strings (avoiding the generator overhead).functools.lru_cacheto a simple fixed-size array cache (since the range is known and contiguous) yields a major speedup—O(1) lookup with no hashing.Here’s the faster version:
Notes:
O(1)list access.mapdue to the avoidance of Python-level function calls per element.If you must preserve the use of @lru_cache for API compatibility:
Your code is already quite optimal. Minor tweak (list comprehension).
But the first method above is substantially faster/more memory efficient if your input domain is tightly bounded as assumed.
✅ Correctness verification report:
🌀 Generated Regression Tests and Runtime
To edit these changes
git checkout codeflash/optimize-_cached_joined-mccv8qo4and push.