Skip to content

Commit

Permalink
Optimize CRC16 calculation (with optimization of slot decision)
Browse files Browse the repository at this point in the history
  • Loading branch information
HeartSaVioR committed Sep 18, 2014
1 parent 9b54744 commit 87f9938
Show file tree
Hide file tree
Showing 2 changed files with 10 additions and 8 deletions.
12 changes: 7 additions & 5 deletions src/main/java/redis/clients/util/JedisClusterCRC16.java
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@
* CRC16 Implementation according to CCITT standard
* Polynomial : 1021 (x^16 + x^12 + x^5 + 1)
*
* @see: http://redis.io/topics/cluster-spec
* @see http://redis.io/topics/cluster-spec
* Appendix A. CRC16 reference implementation in ANSI C
*/
public class JedisClusterCRC16 {
Expand Down Expand Up @@ -36,22 +36,24 @@ public static int getSlot(String key) {
key = key.substring(s+1, e);
}
}
return getCRC16(key) % 16384;
// optimization with modulo operator with power of 2
// equivalent to getCRC16(key) % 16384
return getCRC16(key) & (16384 - 1);
}

/**
* Create a CRC16 checksum from the bytes.
* implementation is from mp911de/lettuce
* implementation is from mp911de/lettuce, modified with some more optimizations
*
* @author <a href="mailto:[email protected]">Mark Paluch</a>
* @param bytes
* @return CRC16 as integer value
* @see https://github.com/xetorthio/jedis/pull/733#issuecomment-55840331
*/
public static int getCRC16(byte[] bytes) {
int crc = 0x0000;

for (byte b : bytes) {
crc = ((crc << 8) ^ LOOKUP_TABLE[((crc >> 8) ^ (b & 0xFF)) & 0xFF]) & 0xFFFF;
crc = ((crc << 8) ^ LOOKUP_TABLE[((crc >>> 8) ^ (b & 0xFF)) & 0xFF]);
}
return crc & 0xFFFF;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,13 +5,13 @@
import redis.clients.util.JedisClusterCRC16;

public class CRC16Benchmark {
private static final int TOTAL_OPERATIONS = 10000000;
private static final int TOTAL_OPERATIONS = 100000000;

private static String[] TEST_SET = {
"", "123456789", "sfger132515", "hae9Napahngaikeethievubaibogiech",
"AAAAAAAAAAAAAAAAAAAAAA", "Hello, World!"
};

public static void main(String[] args) {
long begin = Calendar.getInstance().getTimeInMillis();

Expand All @@ -23,5 +23,5 @@ public static void main(String[] args) {

System.out.println(((1000 * TOTAL_OPERATIONS) / elapsed) + " ops");
}

}

0 comments on commit 87f9938

Please sign in to comment.