Out of Memory in String variable

ByteCarp

Member
Joined
Dec 10, 2008
Messages
9
Programming Experience
5-10
I'm looping through an xml node list and concatenating a string variable with the following:

for x=0 to nl.count-1
temp$=temp$ & nl(x).attributes("text1").value
Next x

I then use the temp$ variable to fill a rich text box:

rtf.text=temp$

I know this isn't a smart way to do things, and an issue I'm running into is an out of memory error on larger nodelists during the loop.

But I can't figure out why because it isn't consistent. The error says the string is causing the error, but the length is well within the usable limits, so I'm thinking I just need a better method than concatenating.

(Note - there is other info being added to the string during the loop, which is why I'm not using a dynamic array, but maybe that's the solution...)

Any ideas?

Thanks.

Carp
 
First up, get rid of that $ symbol. There's never a reason to use that in VB.NET.

As for the problem, the reason is presumably the fact that, each time you concatenate two strings, you are creating a new string object that is the length of the other two combined and then copying the contents of those two into the new one. For example, this:
VB.NET:
Dim str5 As String = str1 & str2 & str3 & str4
actually creates three new String objects. Let's say that str1 to str4 are all 100 characters in length. Instead of just ending up with one new string that is 400 characters in length we'll end up with one that's 200, one that's 300 and one that's 400. If you're concatenating a lot of long strings together that can quickly fill up a lot of memory, plus it's really slow.

What you should be doing is using a StringBuilder. You create a new instance and then call Append repeatedly to add the extra bits. At the end you call ToString to get a single new String object. A StringBuilder will perform better than string concatenation after about one or two dozen substrings and it will immediately use less memory.
 
Back
Top