给定函数f1它接收 n 个字符串参数,就运行时性能而言,什么被认为更好,memcache 的随机密钥生成策略?
我们的 Memcache 客户端对其获取的密钥进行内部 md5sum 哈希处理:
public class MemcacheClient {
public Object get(String key) {
String md5 = Md5sum.md5(key)
// Talk to memcached to get the Serialization...
return memcached(md5);
}
}
我的使用场景是:
第一个选项
public static String f1(String s1, String s2, String s3, String s4) {
String key = s1 + s2 + s3 + s4;
return get(key);
}
第二个选择
/**
* Calculate hash from Strings
*
* @param objects vararg list of String's
*
* @return calculated md5sum hash
*/
public static String stringHash(Object... strings) {
if(strings == null)
throw new NullPointerException("D'oh! Can't calculate hash for null");
MD5 md5sum = new MD5();
// if(prevHash != null)
// md5sum.Update(prevHash);
for(int i = 0; i < strings.length; i++) {
if(strings[i] != null) {
md5sum.Update("_");
md5sum.Update(strings[i].toString()); // Convert to String...
md5sum.Update("_");
} else {
// If object is null, allow minimum entropy by hashing it's position
md5sum.Update("_");
md5sum.Update(i);
md5sum.Update("_");
}
}
return md5sum.asHex();
}
public static String f1(String s1, String s2, String s3, String s4) {
String key = stringHash(s1, s2, s3, s4);
return get(key);
}
请注意,第二个选项可能存在的问题是,我们正在对已经经过 md5sum 处理的摘要结果执行第二个 md5sum(在 memcache 客户端中)。
谢谢阅读,
格言。
- 编辑
用过的MD5实用程序源 http://www.twmacinta.com/myjava/fast_md5_javadocs/com/twmacinta/util/package-summary.html