pkran
pkran

Reputation: 191

Fast Way to compare subarray of bytes

In the scope of a project that I'm currently working, I use binary data stored in arrays of 10 bytes, and I'm trying to find a fast way to compare them. I'm mostly interested in the 5 most significant bytes, so I want to perform a comparison between sub-arrays of bytes. For instance, I have these two parameters:

byte [] indicator = new byte[5];
byte [] current = new byte[10];

I want to see of the 5 first bytes of the 'current' is equal to the 'indicator'. In order to do so, I'm using the Arrays functions, so I'm actually doing the following:

Arrays.equals(indicator, Arrays.copyOfRange(current, 0, 5))

This works fine of course, but not so fast as required. So I strongly believe that there must be a better way to perform such a byte comparison. Maybe by using 0xFF masks???

Any ideas?

Upvotes: 5

Views: 3349

Answers (4)

yofido2535
yofido2535

Reputation: 1

What about:

ByteBuffer.wrap(indicator).equals(ByteBuffer.wrap(current, 0, 5));

(should work in Java 6+, maybe even older)

Upvotes: 0

ZhekaKozlov
ZhekaKozlov

Reputation: 39526

Solution for Java 9+:

Arrays.equals(indicator, 0, 5, current, 0, 5);

Upvotes: 3

Anubian Noob
Anubian Noob

Reputation: 13596

It would be faster just to iterate, as copyOfRange reallocates memory and creates a new array.

public boolean isEqual(byte[] a1, byte[] a2, int size) {
    for(int i=0;i<size;i++)
        if (a1[i] != a2[i])
            return false;
    return true;
}

Upvotes: 3

Dmitry Ginzburg
Dmitry Ginzburg

Reputation: 7461

You may write your helper method, it would be faster, than allocation of a new copy:

public boolean equalsInRange (byte[] arr1, int from1, int to1, byte[] arr2, int from2, int to2) {
    if (to1 - from1 < 0 || to1 - from1 != to2 - from2)
        return false;
    int i1 = from1, i2 = from2;
    while (i1 <= to1) {
        if (arr1[i1] != arr2[i2])
            return false;
        ++i1;
        ++i2;
    }
    return true;
}

Upvotes: 5

Related Questions