Optimize matching loops.

Reported by: Po-Chun Chang

[#264 state:resolved]
[#265 state:resolved]
[#266 state:resolved]