Commit 3b06a1b
authored
⚡️ Speed up function
Here’s an optimized version of your code. The overwhelming majority of time is spent joining and converting numbers to strings (the line with `" ".join(map(str, range(number)))`).
Python's core string join and `str` are already highly optimized, but for further speedup, we can reduce the number of temporary string objects created during joining.
**Preallocating** and using a list comprehension to convert numbers to strings, and then joining, is marginally faster for large numbers.
On Python 3.6+ (as in your version), using `str(i)` is reliable, but using f-strings with list comprehensions is slightly faster.
You may also use the [array module](https://docs.python.org/3/library/array.html), but for string conversion, it's generally not faster.
We will also eliminate unnecessary calculations as their results are not used.
Here's the faster version.
### Notes on the rewrite.
- The preallocated list comprehension with f-strings is faster than `map(str, ...)` in this context according to microbenchmarks.
- Removing the unnecessary variable calculations reduces wasted CPU.
- If extremely high speed is required and the input `number` is always relatively small (up to 1000), you could also precompute all possible outputs and index into the result, at the cost of memory—you can ask for that version if needed.
**Summary**:
The optimization here is mostly removing dead code and making string conversion and joining as fast as Python allows. For huge scale, alternative approaches (precomputing, C extensions) would be needed, but for your requirements, this is the fastest pure Python code.
Let me know if you want advanced (Cython or memcpy) solutions!funcA by 17%1 parent 2a3f344 commit 3b06a1b
File tree
1 file changed
+3
-8
lines changed- code_to_optimize/code_directories/simple_tracer_e2e
1 file changed
+3
-8
lines changedLines changed: 3 additions & 8 deletions
| Original file line number | Diff line number | Diff line change | |
|---|---|---|---|
| |||
3 | 3 | | |
4 | 4 | | |
5 | 5 | | |
6 | | - | |
7 | | - | |
8 | | - | |
| 6 | + | |
9 | 7 | | |
10 | | - | |
11 | | - | |
12 | | - | |
13 | | - | |
14 | | - | |
| 8 | + | |
| 9 | + | |
15 | 10 | | |
16 | 11 | | |
17 | 12 | | |
| |||
0 commit comments