Two quick tweaks. Change _iter_mem_nodes to use sorted order. That way we can sort purely on the 'key' which we know is the sort key anyway. This shaves off a *lot* of time spent in 'sorted()'. Also, if 'references' is in our output nodes, we know we've already checked that it is a valid key, so we don't need to check it again. This shaves another 600ms or so for a bzr.dev tree.