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