Re: match() speed test
- Posted by mattlewis (admin) Dec 11, 2012
- 910 views
Looking for "eleven" was faster even if "x" was before "eleven", and even if i put an "e" in every needle (to attempt tripping up the search for "eleven" (the "e" would hit on every needle)).
How can this be? Is my test defective?
I think that the answer is that with a longer needle, match() stops looking sooner, since there's no point in looking past the last element where the needle could possibly start. Since most of your tests have match() looking at non-matches, the longer needle does many fewer comparisons.
Try shorter haystacks for test1, and you should see the longer needle taking longer to find.
So match does a length test also?
Sort of. It uses a while loop, but stops the loop at the length of the sequence plus one minus the length, since there's no point in looking for the needle to start if there aren't enough elements left from where it's looking.
Matt