Sunday 17 January 2010

Finding an Appointment from the POOM AppointmentCollection

An interesting question was asked on the MSDN forums regarding the retrieval of an Appointment from the POOM AppointmentCollection. The question was related to the performance of such an operation when the AppointmentCollection contained a large number of Appointments. Three proposed approaches where listed however did not provide the performance the user was looking for.

Having read the question and thought about the problem I had an idea about how this problem could be solved. My idea was a "Divide and Conquer" routine. The basic idea behind this routine is that the problem is split into smaller and smaller pieces until the problem is solved. This can be applied to the AppointmentCollection problem in the following way.

From querying the count of items in the AppointmentCollection you know the index of the first item (0) and the last item (the count of items), therefore you can calculate the half way point between these two numbers. The Appointment that corresponds to this half way point is retrieved and its date compared against the date we are searching for. If the date of the queried appointment is less than the date we are searching for then we know that the appointment we are searching for is between the half way point and the last item (the count of items).
In the next iteration the next half way point is calculate using the previous half way point and the last item (the count of items), the appointment is queried and if the appointment date is now greater than the date we are searching for then we know that the appointment must be within the first half of the appointments.
This process continues until the appointment is found.

For my tests I used a range of appointments from the 01/01/2009 to 31/12/2010 (720 Appointments). The test was running on the USA Windows Mobile 5.0 Pocket PC R2 Emulator.
Using a Foreach approach on the AppointmentCollection :-
Time Taken (Average) : 7389ms - Appointments Checked : 382

Using a "Divide and Conquer" approach on the AppointmentCollection :-
Time Taken (Average) : 222ms - Appointments Checked : 12

As you can see there is a great improvement gained from using the "Divide and Conquer" approach.

The source code for this approach is at the following location :-
http://www.smartmobiledevice.co.uk/Projects/FasterAppSearchSample.zip