Skip to main content
.NET Framework 4.6.2+

How to: Use Pageable Collections

  • 3 minutes to read

This example provides a memory usage comparison between the XPCollection and XPCursor instances.

Creating and persisting the objects in the database.

int i;
string dataString = new String('?', 1024);
Session.DefaultSession.ClearDatabase();
Console.WriteLine("Creating objects");
// The loop here creates 1000 objects.
for(i = 0; i<1000; ++i) {
    SampleObject theObject = new SampleObject();
    theObject.Data = dataString;
    theObject.Save();
}

Then we iterate through the contents of the XPCollection and XPCursor and modify the values of the retrieved objects. We assess the amount of memory allocated every time one hundred objects have been modified.

GC.Collect();
i = 0;
Console.WriteLine("Processing objects with XPCursor");
XPCursor cursor = new XPCursor(Session.DefaultSession, typeof(SampleObject));
cursor.PageSize = 100;
// Loop through all the objects.
foreach(SampleObject theObject in cursor) {
    theObject.Data = new String('!', 1024);
    theObject.Save();
    ++i;
     // Every 100 objects write out memory used.
    if(i % 100 == 0)
Console.WriteLine(String.Format("Object {0}, memory allocated {1}", i, GC.GetTotalMemory(true)));
}

GC.Collect();
i = 0;
Console.WriteLine("Processing objects with XPCollection");
using(XPCollection collection = new XPCollection(Session.DefaultSession, typeof(SampleObject))) {
// Loop through all the objects.
    foreach(SampleObject theObject in collection) {
        theObject.Data = new String('@', 1024);
        theObject.Save();
        ++i;
        if(i % 100 == 0)
            // Every 100 objects write out memory used.
            Console.WriteLine(String.Format("    Object {0}, memory allocated {1}", i, 
              GC.GetTotalMemory(true)));
    }
}

The table below shows the result:

Processing objects with XPCursor

Processing objects with XPCollection

Object 100, memory allocated 382752

Object 200, memory allocated 389152

Object 300, memory allocated 395552

Object 400, memory allocated 386336

Object 500, memory allocated 392736

Object 600, memory allocated 386336

Object 700, memory allocated 392736

Object 800, memory allocated 386336

Object 900, memory allocated 392736

Object 1000, memory allocated 386036

Object 100, memory allocated 2568928

Object 200, memory allocated 2568504

Object 300, memory allocated 2568504

Object 400, memory allocated 2568504

Object 500, memory allocated 2568504

Object 600, memory allocated 2568492

Object 700, memory allocated 2568492

Object 800, memory allocated 2568492

Object 900, memory allocated 2568492

Object 1000, memory allocated 2568492

From the output you can see that the XPCursor has significantly improved the way in which memory is allocated for the collection’s contents.