Here's a faster version of Ergwun's excellent answer :
static int SearchBytes( byte[] haystack, byte[] needle ) {
var len = needle.Length;
var limit = haystack.Length - len;
for( var i = 0; i <= limit; i++ ) {
var k = 0;
for( ; k < len; k++ ) {
if( needle[k] != haystack[i+k] ) break;
}
if( k == len ) return i;
}
return -1;
}
In a short test with an 11-megabyte hay and a 9-byte needle, this was about three times faster.
Optimization:
- No function call every time through an external loop.
- Needle length and search limit are cached.
-
match().
, - Boyer-Moore, , , , , .