Commit ddf1cd0
authored
⚡️ Speed up function
Certainly! The **biggest bottleneck** in your code is the last line.
This is because string conversion and joining are relatively expensive, especially when repeated.
### Optimization strategies
1. **Avoid unnecessary calculations**:
`k` and `j` are calculated but unused. We can safely remove these lines for further optimization, **unless** you kept them for side-effect or debug purposes (your line profiling suggests they're dead code).
2. **Faster int-to-str joining**.
- **Precompute lookup for str(n) for small n**.
- Specialized approach for `number <= 1000` (since you cap number at 1000).
- Use a list comprehension and call `" ".join()` just once.
- For even further optimization, use `array` module for preallocated data, but for under 1000 elements the gain is marginal.
### Rewrite
Here is an optimized version using a tuple lookup for string conversions, which is faster than repeatedly calling `str(n)`, and removes dead code.
#### Why this is faster
- **Avoids str() lookup for each join element**, since string conversion is done in a batch with list comprehension, which is faster than map(str, ...), especially for small numbers.
- **Removes dead code** computing `k` and `j`.
- For the actual join, `join` is as fast as it can be, but reducing per-element work (as above) helps.
---
### (OPTIONAL) Precomputed cache version
If `funcA(number)` will be called many times with the **same `number` values**, you might *precompute* all such strings for number in [0, 1000].
This is **very fast** for repeated calls, at the cost of a few KB of memory.
---
Let me know if you want this extreme version, but for most purposes the list comprehension is the fastest idiomatic way in CPython for this operation.
---
**Final optimized version:**
This should run significantly faster for typical usage.funcA by 10%1 parent ad6caf3 commit ddf1cd0
File tree
1 file changed
+5
-9
lines changed- code_to_optimize/code_directories/simple_tracer_e2e
1 file changed
+5
-9
lines changedLines changed: 5 additions & 9 deletions
| Original file line number | Diff line number | Diff line change | |
|---|---|---|---|
| |||
3 | 3 | | |
4 | 4 | | |
5 | 5 | | |
6 | | - | |
7 | | - | |
8 | | - | |
9 | | - | |
10 | | - | |
11 | | - | |
12 | | - | |
13 | | - | |
14 | | - | |
| 6 | + | |
| 7 | + | |
| 8 | + | |
| 9 | + | |
| 10 | + | |
15 | 11 | | |
16 | 12 | | |
17 | 13 | | |
| |||
0 commit comments