I'm currently creating an Android app (which would be finished by now if I didn't keep finding annoying niggles) which, since it's a todo list app, consists of lots of lists. Occasionally a lot of items in these lists need to be updated - for instance, when the item order is rearranged then any items affected need to have their new position in the list saved to the database.

Initially I used a simple for loop to move through each item in the list (pseudo code):

for(int i = 0; i < list.length; i++) {
    updatePosition(i);
}

Unfortunately, this was noticeably laggy when updating lists, and for lists with a lot of items it was even worse!

My next loop was slightly better - this one would only update items which where lower in the list than where the rearranged item ended up:

// to and from are ints passed in to this function
// and represent the starting and end position of the item
int max = to;
if(from > to) {
    max = from;
}

for(int i = 0; i < max + 1; i++) {
    updatePosition(i);
}

This worked much better than the first loop since fewer items were being updated. However, items towards the bottom of the list would still lag compared with items towards the top, since the loop always started from 0 (the first position in the list). Obviously, this could be improved:

int min = from;
int max = to;
if(from > to) {
    min = to;
    max = from;
}

for(int i = min; i < max + 1; i++) {
    updatePosition(i);
}

This final version of the loop meant the updating the list was much faster than before, and felt a lot less laggy. Hooray!