在我的笔记本电脑上,String
直接设置总是比设置好byte[]
,即使Serialization mechanism
我用Jedis
. 我很困惑是否String
应该在调用 jedis 时进行序列化set(String, String)
?如果Serialization mechanism
发生,不是我在SerializeUtil
下面写的默认机制吗?我的代码如下:
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));
}
也许SerializeUtil
是需要:
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;
}
有谁能告诉我为什么?
将String
操作替换+
为StringBuilder
,现在set(String, String)
仍然比其他方法更快。
另一个问题,是否有必要serialize
在使用set(byte[], byte[])
或仅调用时将字符串转换为字节String.getBytes[]
?