Thursday, July 31, 2014

How to optimize string allocation?

Here is the code...



private char[] buffer = new char[32];

internal string ExtractString(int len)
{
if (len > buffer.Length)
{
// the buffer is too small, make it bigger
Array.Resize(ref buffer, buffer.Length * 2);
}

for (int i = 0; i < len; i++)
buffer[i] = (char)_data[_currentIndex++];

return new string(buffer, 0, len);
}

The profiler shows that the hot spot of this method is "new string(buffer, 0, len)". Anyway to optimize this?


I am thinking to keep the result string in Dictionary and then searching buffer[] in Dictionary to not allocate the string again if it does exist in the Dictionary. Would this help improve the performance? but I am not sure how to search buffer[] in Dictionary with vary length, any example?




atanai


No comments:

Post a Comment