# Efficient byte sequence detection

I seek the assessment of which code block is more efficient in Java at detecting the byte sequence of

00 00 00 01


and

00 00 01


in a byte array.

Version 1

for (int i = 0; i < frame.length - 4; i++) {
if (frame[i] == 0) {
if (frame[i + 1] == 0) {
if (frame[i + 2] == 0) {
if (frame[i + 3] == 1) {
// found marker 00 00 00 01
// do work here
}
} else {
if (frame[i + 2] == 1) {
// found marker 00 00 01
// do work here
}
}
}
}
}


Version 2

    for (int i = 0; i < frame.length - 4; i++) {
if (frame[i] == 0 && frame[i + 1] == 0 && frame[i + 2] == 0 && frame[i + 3] == 1) {
// found marker 00 00 00 01
// do work here
} else if (frame[i] == 0 && frame[i + 1] == 0 && frame[i + 2] == 1) {
// found marker 00 00 01
// do work here
}
}


Application repo

• Simple code analysis would suggest that version 1 is better because segments 1 and 2 are not checked twice in case it's 00 00 01. I'm not sure if the Java compiler does not do any smart optimizations here, although I'm not really sure what more it could do. Dec 29, 2014 at 23:18
• Be aware that if you're not also requesting a review of this code, then it's off-topic. Answers solely giving an opinion on the better version will not work here. Dec 30, 2014 at 8:11
• I'm looking for an assessment of the blocks, if an answer contains an opinion then its an off-topic answer and should not impact the question. Dec 30, 2014 at 13:08

Version 3

Consider the case of a sequence of 00 00 00 02. This sequence will pass the first 3 if conditions and fail at the 4th one. But what does this tell you ? It tells you that instead of increasing i by 1 it should be increased by 4.

This idea converted to code could look like this

for (int i = 0; i < frame.length - 4; i++) {

if (frame[i] != 0) {
continue;
}

i++;
if (frame[i] != 0) {
continue;
}

i++;
if (frame[i] > 1) {
continue;
}

if (frame[i] == 1) {
// found marker 00 00 01
// do work here

continue;
}

i++;
if (frame[i] == 1) {
// found marker 00 00 00 01
// do work here
}
}


which isn't easy to read/understand at first glance, so a big comment about why the increasing of i is done like this would be in order.