Commit 171c028
committed
Optimize Python C extension readStruct for nested structs
In this area of code, there already exists an optimization where we skip calling `klass(**kwargs)` on the top-level struct and instead init an empty object then PyObject_SetAttr the properties onto it.
This was done because Python's keyword
argument matching is O(n) string comparisons per argument, making this expensive for structs with many fields.
However, nested structs which are decoded within the C extension did not get this same optimization, causing them to go through the slow class initialization path.
In this change, for mutable nested structs, we create the instance up front with a no-arg constructor (klass()) and set decoded fields directly via PyObject_SetAttr (the same way we fast-path the top-level struct).
Immutable structs (TFrozenBase subclasses) continue to use the kwargs
path since their generated __setattr__ blocks attribute mutation.
Immutability is detected via PyObject_IsSubclass against TFrozenBase,
with the class reference cached in a function-local static.
Benchmarks show up to 3.6x speedup for deeply nested struct hierarchies, with no impact on flat structs. I had Claude generate me some benchmarks to showcase performance in different nested scenarios.
Note the test change. I asked about potentially changing this to look more like what the codegen produces here https://github.com/apache/thrift/pull/3349/changes#r3026288637. Currently, this fails because its not marked as frozen but has a erroring setattr1 parent 197da84 commit 171c028
2 files changed
Lines changed: 36 additions & 8 deletions
| Original file line number | Diff line number | Diff line change | |
|---|---|---|---|
| |||
874 | 874 | | |
875 | 875 | | |
876 | 876 | | |
877 | | - | |
| 877 | + | |
878 | 878 | | |
| 879 | + | |
879 | 880 | | |
880 | 881 | | |
881 | 882 | | |
882 | 883 | | |
883 | | - | |
884 | | - | |
885 | | - | |
886 | | - | |
887 | | - | |
| 884 | + | |
| 885 | + | |
| 886 | + | |
| 887 | + | |
| 888 | + | |
| 889 | + | |
| 890 | + | |
| 891 | + | |
| 892 | + | |
| 893 | + | |
| 894 | + | |
| 895 | + | |
| 896 | + | |
| 897 | + | |
| 898 | + | |
| 899 | + | |
| 900 | + | |
| 901 | + | |
| 902 | + | |
| 903 | + | |
| 904 | + | |
| 905 | + | |
| 906 | + | |
| 907 | + | |
| 908 | + | |
| 909 | + | |
| 910 | + | |
| 911 | + | |
| 912 | + | |
888 | 913 | | |
889 | 914 | | |
890 | 915 | | |
| |||
| Original file line number | Diff line number | Diff line change | |
|---|---|---|---|
| |||
56 | 56 | | |
57 | 57 | | |
58 | 58 | | |
| 59 | + | |
59 | 60 | | |
60 | 61 | | |
61 | 62 | | |
62 | 63 | | |
63 | | - | |
| 64 | + | |
64 | 65 | | |
65 | 66 | | |
| 67 | + | |
| 68 | + | |
66 | 69 | | |
67 | 70 | | |
68 | 71 | | |
69 | 72 | | |
70 | 73 | | |
71 | 74 | | |
72 | | - | |
| 75 | + | |
73 | 76 | | |
74 | 77 | | |
75 | 78 | | |
| |||
0 commit comments