< Day Day Up > |
3.9 Optimizing StringBuilder Performance
TechniqueUse the EnsureCapacity method in the StringBuilder class. Set this integral value to a value that signifies the length of the longest string you may store in this buffer. CommentsThe StringBuilder class contains methods that allow you to expand the memory of the internal buffer based on the size of the string you may store. As your string continually grows, the StringBuilder won't have to repeatedly allocate new memory for the internal buffer. In other words, if you attempt to place a larger length string than what the internal buffer of the StringBuilder class can accept, then the class will have to allocate additional memory to accept the new data. If you continuously add strings that increase in size from the last input string, the StringBuilder class will have to allocate a new buffer size, which it does internally by calling the GetStringForStringBuilder method defined in the System.String class. This method ultimately calls the unmanaged method FastAllocateString . By giving the StringBuilder class a hint using the EnsureCapacity method, you can help alleviate some of this continual memory reallocation, thereby optimizing the StringBuilder performance by reducing the amount of memory allocations needed to store a string value. |
< Day Day Up > |