2
\$\begingroup\$

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

\$\endgroup\$
3
  • \$\begingroup\$ 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. \$\endgroup\$ – Łukasz Zwierko Dec 29 '14 at 23:18
  • \$\begingroup\$ 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. \$\endgroup\$ – Jamal Dec 30 '14 at 8:11
  • \$\begingroup\$ 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. \$\endgroup\$ – Paul Gregoire Dec 30 '14 at 13:08
1
\$\begingroup\$

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.

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.