It's hard to tell from your "code" but it looks like you have multiple sets (the elsif part) of criteria and are looping over the complete pair of arrays, checking for each criterium. This is of course straightforward. The only room for optimization probably is in "the first index position where a simple set of criteria are met". The idea is to short-circuit the loop as fast as possible. Two possibilities come to (my) mind: