On my laptop, set String
directly is always proformace better than set byte[]
, even with Serialization mechanism
when I test with Jedis
. I am confused that if String
should be serialized when call jedis set(String, String)
? If Serialization mechanism
happend, isn't is the default mechaism as I write in my SerializeUtil
below?
My code is below:
public void testRedis() {
long startTime = System.currentTimeMillis();
for (int i = 0; i < count; i++) {
StringBuilder sb = new StringBuilder(str);
sb.append(i);
jedis.set(sb.toString(), value);
}
long endTime = System.currentTimeMillis();
System.out.println("default: " + (endTime - startTime));
startTime = System.currentTimeMillis();
for (int i = 0; i < count; i++) {
StringBuilder sb = new StringBuilder(str);
sb.append(i);
jedis.set(sb.toString().getBytes(), value.getBytes());
}
endTime = System.currentTimeMillis();
System.out.println("byte: " + (endTime - startTime));
startTime = System.currentTimeMillis();
for (int i = 0; i < count; i++) {
StringBuilder sb = new StringBuilder(str);
sb.append(i);
jedis.set(SerializeUtil.serDefaultString(sb.toString()), SerializeUtil.serDefaultString(value));
}
endTime = System.currentTimeMillis();
System.out.println("default ser: " + (endTime - startTime));
startTime = System.currentTimeMillis();
for (int i = 0; i < count; i++) {
StringBuilder sb = new StringBuilder(str);
sb.append(i);
jedis.set(SerializeUtil.serUTFString(sb.toString()), SerializeUtil.serUTFString(value));
}
endTime = System.currentTimeMillis();
System.out.println("utf ser: " + (endTime - startTime));
}
Maybe SerializeUtil
is need :
public static byte[] serDefaultString(String data) {
byte[] result = null;
ObjectOutputStream oos = null;
ByteArrayOutputStream byteArray = new ByteArrayOutputStream();
try {
oos = new ObjectOutputStream(byteArray);
try {
oos.writeObject(data);
oos.flush();
result = byteArray.toByteArray();
} finally {
oos.close();
}
} catch(IOException e) {
e.printStackTrace();
}
return result;
}
public static byte[] serUTFString(String data) {
byte[] result = null;
ObjectOutputStream oos = null;
ByteArrayOutputStream byteArray = new ByteArrayOutputStream();
try {
oos = new ObjectOutputStream(byteArray);
try {
oos.writeUTF(data);
oos.flush();
result = byteArray.toByteArray();
} finally {
oos.close();
}
} catch (Exception e) {
e.printStackTrace();
}
return result;
}
Is anyone can tell me why?
Replace String
operation +
to StringBuilder
, now set(String, String)
is still faster than other approach.
Another question, Is it necessary to serialize
String to bytes when work with set(byte[], byte[])
or just call String.getBytes[]
?