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:
在我目前工作的项目范围内,我使用存储在10字节数组中的二进制数据,并试图找到一种快速比较它们的方法。我最感兴趣的是5个最重要的字节,所以我想对字节的子数组进行比较。例如,我有两个参数:
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:
我想看到5个第一个字节的“电流”等于“指示器”。为了做到这一点,我使用了数组函数,所以实际上我在做下面的事情:
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???
这当然很有效,但没有要求的那么快。所以我坚信一定有更好的方法来执行这样的字节比较。也许用0xFF掩码???
Any ideas?
什么好主意吗?
2 个解决方案
#1
3
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;
}
#2
2
It would be faster just to iterate, as copyOfRange
reallocates memory and creates a new array.
只是迭代会更快,因为copyOfRange重新分配内存并创建一个新数组。
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;
}
#1
3
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;
}
#2
2
It would be faster just to iterate, as copyOfRange
reallocates memory and creates a new array.
只是迭代会更快,因为copyOfRange重新分配内存并创建一个新数组。
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;
}