我编写了一个函数,用于将 64 位整数转换为基数 62 字符串。最初,我是这样实现的:
char* charset = " 0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
int charsetLength = strlen(charset);
std::string integerToKey(unsigned long long input)
{
unsigned long long num = input;
string key = "";
while(num)
{
key += charset[num % charsetLength];
num /= charsetLength;
}
return key;
}
然而,这太慢了。
我通过提供生成查找表的选项来提高速度。该表的大小约为 62 4 个字符串,生成如下:
// Create the integer to key conversion lookup table
int lookupChars;
if(lookupDisabled)
lookupChars = 1;
else
largeLookup ? lookupChars = 4 : lookupChars = 2;
lookupSize = pow(charsetLength, lookupChars);
integerToKeyLookup = new char*[lookupSize];
for(unsigned long i = 0; i < lookupSize; i++)
{
unsigned long num = i;
int j = 0;
integerToKeyLookup[i] = new char[lookupChars];
while(num)
{
integerToKeyLookup[i][j] = charset[num % charsetLength];
num /= charsetLength;
j++;
}
// Null terminate the string
integerToKeyLookup[i][j] = '\0';
}
实际的转换如下所示:
std::string integerToKey(unsigned long long input)
{
unsigned long long num = input;
string key = "";
while(num)
{
key += integerToKeyLookup[num % lookupSize];
num /= lookupSize;
}
return key;
}
这大大提高了速度,但我仍然相信它可以改进。32 位系统上的内存使用量约为 300 MB,而 64 位系统上则超过 400 MB。似乎我应该能够减少内存和/或提高速度,但我不确定如何。
如果有人可以帮助我弄清楚如何进一步优化此表,我将不胜感激。