【发布时间】:2011-02-08 07:21:05
【问题描述】:
给定函数 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 utility source
【问题讨论】:
标签: java algorithm md5 memcached