我需要为每个客户生成大约500k的唯一代码。
代码在几分钟内运行,但是,我需要确保没有冲突,所以我添加了这个逻辑以使用HashTable。这导致性能超过8小时,仅产生20万。
有什么我可以用来改善这里的表现吗?
性能瓶颈是HashSet查找(第8行)。还有哪些其他选项可以提高确保没有重复的性能?
public string GenerateUniqueReferralCode(CustomerObj customer, HashSet<string> assignedCodes)
{
bool isUnique = false;
string code = String.Empty;
do
{
code = GenerateReferralCode(customer);
if (!assignedCodes.Contains(code))
{
isUnique = true;
}
else
{
isUnique = false;
}
} while (!isUnique);
return code;
}
public string GenerateReferralCode(CustomerObj customer)
{
var code = String.Empty;
//replace special characters and only keep alpha
var name = customer.Profile.FirstName + customer.Profile.LastName;
name = new String(name.Where(Char.IsLetter).ToArray());
if (name.Length > 3)
{
code += name.Substring(0, 4).ToUpperInvariant();
}
else
{
code += customer.Profile.FirstName.Substring(0, customer.Profile.FirstName.Length).ToUpperInvariant();
}
code += CreateMD5(customer.Profile.Email + DateTime.UtcNow.ToString());
code = code.Substring(0, 7);
return code;
}
与现代处理器的速度相比,DateTime.UtcNow
以冰川率变化,这似乎是您生成代码时随机性的唯一来源1。也无法恢复此值并验证MD52哈希,所以我不确定它添加了什么值。
相反,使用加密随机数生成器生成一些真正的随机性并在您的代码中使用它。但是,如果您需要验证哈希值,请不要忘记在代码中包含原始值。
1这意味着你很可能花费年龄来循环创建与之前代码精确匹配的“新”代码,直到时间变化为止。
2N.B.你不应该在新工作中使用MD5 ......