@@ -200,6 +200,71 @@ specified conventions, then passing it to the
200
200
var camelCaseConvention = new ConventionPack { new CamelCaseElementNameConvention() };
201
201
ConventionRegistry.Register("CamelCaseConvention", camelCaseConvention, t => true);
202
202
203
+ .. _csharp-array-serialization:
204
+
205
+ Improve Array Serialization Performance
206
+ ---------------------------------------
207
+
208
+ You can improve your application's performance by representing
209
+ arrays of primitives as `Memory<T> <https://learn.microsoft.com/en-us/dotnet/api/system.memory-1?view=net-8.0>`__
210
+ and `ReadOnlyMemory<T> <https://learn.microsoft.com/en-us/dotnet/api/system.readonlymemory-1?view=net-8.0>`__
211
+ structs instead of by using types such as standard {+language+} arrays or
212
+ ``BsonArray`` objects. The driver implements fast serialization and
213
+ deserialization paths for ``Memory<T>`` and ``ReadOnlyMemory<T>``, which
214
+ enhances speed and reduces memory usage.
215
+
216
+ .. note::
217
+
218
+ Truncation and overflow checks are not supported for ``Memory<T>`` or
219
+ ``ReadOnlyMemory<T>``, but these checks are implemented for standard
220
+ arrays.
221
+
222
+ You can effect these performance improvements by storing the following
223
+ primitive types in ``Memory<T>`` or ``ReadOnlyMemory<T>`` structs:
224
+
225
+ - ``bool``
226
+ - ``sbyte``
227
+ - ``byte``
228
+ - ``char``
229
+ - ``short``
230
+ - ``ushort``
231
+ - ``int``
232
+ - ``uint``
233
+ - ``long``
234
+ - ``ulong``
235
+ - ``float``
236
+ - ``double``
237
+ - ``decimal``
238
+
239
+ The following example defines a ``Line`` POCO that contains array fields
240
+ modeled by ``Memory`` and ``ReadOnlyMemory`` structs:
241
+
242
+ .. literalinclude:: /includes/fundamentals/code-examples/MemorySerialization.cs
243
+ :start-after: start-line-class
244
+ :end-before: end-line-class
245
+ :language: csharp
246
+ :dedent:
247
+
248
+ The following document represents how a sample ``Line`` object is
249
+ represented in MongoDB:
250
+
251
+ .. code-block:: json
252
+
253
+ {
254
+ "_id": ...,
255
+ "X": [ 1, 2, 3, 4, 5 ],
256
+ "Y": [ 1, 1.409999966621399, 1.7300000190734863, 2, 2.240000009536743 ]
257
+ }
258
+
259
+ .. tip:: Model Vectors
260
+
261
+ :ref:`csharp-atlas-vector-search` involves creating and querying
262
+ large numerical arrays. If your application uses
263
+ {+vector-search+}, you might benefit from the performance
264
+ improvements from using ``Memory`` and ``ReadOnlyMemory`` to store
265
+ array representations of embeddings and query vectors. To learn more,
266
+ see :ref:`csharp-supported-vector-types` in the {+vector-search+} guide.
267
+
203
268
Additional Information
204
269
----------------------
205
270
0 commit comments