Reputation: 61433
I have an in-memory byte[]
and need to locate the offset where 13
and 10
are. I will then use the following to extract that line:
String oneLine = Encoding.ASCII.GetString(bytes, 0, max);
What is the fastest way to search for the two bytes on a x64 bit computer? ..and convert it to a string?
Is there anything I can do other than iterating through each byte, scanning for 13
and then scan for 10
?
// Disclaimer:
// This is just for my curiosity. Perhaps I'll gain a better understanding of
// how .NET interfaces with RAM, the CPU instructions related to comparisons, etc.
//
// I don't suspect a performance problem, but I do suspect a lack of understanding
// (on my part) on how C# does low-level operations.
Upvotes: 3
Views: 1587
Reputation: 3060
Since you are looking for a two byte sequence, you don't have to scan every byte, just every other one. If the target index contains a 13, then look at the next byte for a 10. If the target index contatins a 10, look at the previous byte for a 13. That should cut your scan time approximatly in half over a linear search.
Upvotes: 1
Reputation: 2758
Not sure if it will be 'the fastest way' but you can look at Boyer-Moore algorithm to find the indexes of the required values.
Have a look at this SO thread Search longest pattern in byte array in C#
Boyer-Moore would be better than a linear array traversal because it can skip elements depending on the length of you 'needle' and it gets better as the 'haystack' gets bigger. HTH.
Upvotes: 1