我有一个应用程序需要将数百万个 char* 作为输入参数(通常是少于 512 个字符的字符串(在 unicode 中)),并将它们转换并存储为 .net 字符串。
事实证明它是我应用程序性能的真正瓶颈。我想知道是否有一些设计模式或想法可以使其更有效。
有一个关键部分让我觉得它可以改进:有很多重复项。假设有 100 万个对象进入,可能只有 50 个独特的 char* 模式。
作为记录,这里是我用来将 char* 转换为字符串的算法(该算法在 C++ 中,但项目的其余部分在 C# 中)
String ^StringTools::MbCharToStr ( const char *Source )
{
String ^str;
if( (Source == NULL) || (Source[0] == '\0') )
{
str = gcnew String("");
}
else
{
// Find the number of UTF-16 characters needed to hold the
// converted UTF-8 string, and allocate a buffer for them.
const size_t max_strsize = 2048;
int wstr_size = MultiByteToWideChar (CP_UTF8, 0L, Source, -1, NULL, 0);
if (wstr_size < max_strsize)
{
// Save the malloc/free overhead if it's a reasonable size.
// Plus, KJN was having fits with exceptions within exception logging due
// to a corrupted heap.
wchar_t wstr[max_strsize];
(void) MultiByteToWideChar (CP_UTF8, 0L, Source, -1, wstr, (int) wstr_size);
str = gcnew String (wstr);
}
else
{
wchar_t *wstr = (wchar_t *)calloc (wstr_size, sizeof(wchar_t));
if (wstr == NULL)
throw gcnew PCSException (__FILE__, __LINE__, PCS_INSUF_MEMORY, MSG_SEVERE);
// Convert the UTF-8 string into the UTF-16 buffer, construct the
// result String from the UTF-16 buffer, and then free the buffer.
(void) MultiByteToWideChar (CP_UTF8, 0L, Source, -1, wstr, (int) wstr_size);
str = gcnew String ( wstr );
free (wstr);
}
}
return str;
}
最佳答案
您可以使用输入字符串中的每个字符来提供 trie结构体。在叶子处,有一个 .NET 字符串对象。然后,当您之前看到的 char*
出现时,您可以快速找到现有的 .NET 版本,而无需分配任何内存。
伪代码:
- 从一个空的 trie 开始,
- 通过搜索 trie 来处理一个 char* 直到你不能再继续了
- 添加节点,直到整个 char* 都被编码为节点
- 在叶子上,附加一个实际的 .NET 字符串
这个其他 SO 问题的答案应该可以帮助您入门:How to create a trie in c#
关于c# - 优化数百万个 char* 到字符串的转换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14325505/