I wonder if there is any need to sort
the keys of your outer and middle loop. If you are looking for any, even small, time-savings, here might be a quick bonus.
A program should be light and agile, its subroutines connected like a string of pearls. The spirit and intent of the program should be retained throughout. There should be neither too little or too much, neither needless loops nor useless variables, neither lack of structure nor overwhelming rigidity." - The Tao of Programming, 4.1 - Geoffrey James
My blog: Imperial Deltronics