optimizations to matching algorithm