Commit d8d5868
authored
⚡️ Speed up function
Here is the optimized version of your program, focusing on speeding up the slow path in `make_cfapi_request`, which is dominated by `json.dumps(payload, indent=None, default=pydantic_encoder)` and the use of `requests.post(..., data=json_payload, ...)`.
Key optimizations.
- **Use `requests.post(..., json=payload, ...)`:** This lets `requests` do the JSON serialization more efficiently (internally uses `json.dumps`). Furthermore, `requests` will add the `Content-Type: application/json` header if you use the `json` argument.
- **Only use the custom encoder if really needed:** Only pass `default=pydantic_encoder` if payload contains objects requiring it. If not, the standard encoder is much faster. You can try a direct serialization, and fallback if a `TypeError` is raised.
- **Avoid repeated `.upper()`** inside the POST/GET dispatch by normalizing early.
- **Avoid unnecessary string interpolation.**
- **Avoid updating headers dict when not needed.**
- **Other micro-optimizations:** Use local variables, merge dicts once, etc.
with all comments preserved and only modified/added where code changed.
**Explanation of biggest win:**
The largest bottleneck was in JSON encoding and in manually setting the content-type header. Now, `requests.post(..., json=payload)` is used for the fastest path in the vast majority of requests, only falling back to a slower path if necessary. This should substantially speed up both serialization and POST.
This approach is backward-compatible and will produce exactly the same results as before.is_function_being_optimized_again by 44% in PR #275 (dont-optimize-repeatedly-gh-actions)1 parent f2733b3 commit d8d5868
1 file changed
+30
-16
lines changed| Original file line number | Diff line number | Diff line change | |
|---|---|---|---|
| |||
1 | 1 | | |
2 | 2 | | |
3 | | - | |
4 | 3 | | |
5 | 4 | | |
6 | 5 | | |
7 | 6 | | |
8 | 7 | | |
9 | | - | |
| 8 | + | |
10 | 9 | | |
11 | 10 | | |
12 | 11 | | |
13 | 12 | | |
| 13 | + | |
14 | 14 | | |
15 | 15 | | |
16 | 16 | | |
17 | 17 | | |
18 | | - | |
19 | 18 | | |
20 | 19 | | |
21 | 20 | | |
| |||
43 | 42 | | |
44 | 43 | | |
45 | 44 | | |
46 | | - | |
| 45 | + | |
| 46 | + | |
47 | 47 | | |
48 | | - | |
49 | | - | |
50 | | - | |
51 | | - | |
52 | | - | |
| 48 | + | |
| 49 | + | |
| 50 | + | |
| 51 | + | |
| 52 | + | |
| 53 | + | |
| 54 | + | |
| 55 | + | |
| 56 | + | |
| 57 | + | |
| 58 | + | |
| 59 | + | |
| 60 | + | |
| 61 | + | |
| 62 | + | |
53 | 63 | | |
54 | | - | |
| 64 | + | |
55 | 65 | | |
56 | 66 | | |
57 | 67 | | |
| |||
200 | 210 | | |
201 | 211 | | |
202 | 212 | | |
203 | | - | |
204 | | - | |
205 | | - | |
206 | | - | |
207 | | - | |
208 | | - | |
| 213 | + | |
209 | 214 | | |
210 | 215 | | |
211 | 216 | | |
| 217 | + | |
| 218 | + | |
| 219 | + | |
| 220 | + | |
| 221 | + | |
| 222 | + | |
| 223 | + | |
| 224 | + | |
| 225 | + | |
0 commit comments