You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
feat: Implement collection count optimization for collection deserialization, including a new [GenJsonSkipCountOptimization] attribute and updated documentation.
Copy file name to clipboardExpand all lines: README.md
+23Lines changed: 23 additions & 0 deletions
Display the source diff
Display the rich diff
Original file line number
Diff line number
Diff line change
@@ -289,6 +289,29 @@ public partial class Cat : Animal
289
289
290
290
**Deserialization**: `Animal.FromJson(...)` will inspect the `$type` property and deserialize into the correct derived type (`Dog` or `Cat`). If the type is unknown or missing (for abstract bases), it returns `null`.
291
291
292
+
### 11. Collection Count Optimization
293
+
294
+
GenJson optimizes collection deserialization (Lists, Arrays, Dictionaries) by pre-allocating the collection with the exact size. This avoids resizing overhead during population.
295
+
296
+
**How it works:**
297
+
-**Serialization**: The generator automatically emits a hidden property named after the collection with a `$` prefix (e.g., `"$MyList": 5`) immediately before the collection property.
298
+
-**Deserialization**: The parser reads this count property first and initializes the collection with the correct capacity (e.g., `new List<int>(5)`).
299
+
300
+
> [!NOTE]
301
+
> GenJson can still parse standard JSON without the count property. If the property is missing, it will automatically fall back to standard resizing behavior.
302
+
303
+
**Disabling Optimization:**
304
+
If you need strictly standard JSON or cannot support the extra property, you can disable this optimization using the `[GenJsonSkipCountOptimization]` attribute on your class or struct.
305
+
306
+
```csharp
307
+
[GenJson]
308
+
[GenJsonSkipCountOptimization] // Disables usage of $MyList property
309
+
publicpartialclassMyClass
310
+
{
311
+
publicList<int> MyList { get; set; }
312
+
}
313
+
```
314
+
292
315
## How It Works
293
316
294
317
GenJson analyzes your code during compilation and generates specialized serialization code.
sb.AppendLine(" if (!global::GenJson.GenJsonParser.TryExpect(json, ref index, ':')) return null;");
1185
-
GenerateParseValue(sb,prop.Type,"_"+prop.Name," ",0,(prop.TypeisGenJsonDataType.Enumerable or GenJsonDataType.Dictionary)?$"_{prop.Name}_count":null);
1188
+
GenerateParseValue(sb,prop.Type,"_"+prop.Name," ",0,(!data.SkipCountOptimization&&(prop.TypeisGenJsonDataType.Enumerable or GenJsonDataType.Dictionary))?$"_{prop.Name}_count":null);
0 commit comments