Wednesday, April 13, 2005

Be careful when doing lot of operations on strings

If your code has lot of string manipulation within it, you have to take a gentle care of the way you write your code. For example take a look at the following code snippet.
string str = Hello Bob;
str += & Alice;
As you see, you may assume that your code will allocate memory for only two strings. Actually your assumption is too bad this time. In .Net when you concatenate two strings it returns a COPY of the modified string. Therefore there will be 3 allocations for 3 strings in the above code execution.
I'm pretty sure now you be wondering "why make a big fuzz for a single string concatenation line?" Actually your thinking is quiet good this time. Your code will not gain any significant performance issue with a single operation. But as the number of string operations grows up you code will tend to notice performance issues. The reason for this is, the runtime allocates memory for each any every copy of string.
Thanx to microsoft,
StringBuilder class, alternative approach to overcome this problem, is there. Always try to use StringBuilder class when you are dealing with string operations.
StringBuilder provides a rich set of functionality to do almost everything that you wanna do with a string. You could do the above operation as follows with the StringBuilder class.

StringBuilder sb = new StringBuilder("Hello Bob");
sb.Append("& Alice");
Even though you use StringBuilder, make sure you are aware of the reallocations. :-) So you can use
sb.Capacity = 20;
to specify the initial capacity you want for the final string. That makes sure that the reallocations happen when you reached the maximum number of characters.
Happy Programming!

0 Comments:

Post a Comment

<< Home