What is the longest string that can be created in .NET? The docs for the String
class are silent on this question as far as I can see, so an authoritative answe
For anyone coming to this topic late, I could see that hitscan's "you probably shouldn't do that" might cause someone to ask what they should do…
The StringBuilder class is often an easy replacement. Consider one of the stream-based classes especially, if your data is coming from a file.
The problem with s += "stuff"
is that it has to allocate a completely new area to hold the data and then copy all of the old data to it plus the new stuff - EACH AND EVERY LOOP ITERATION. So, adding five bytes to 1,000,000 with s += "stuff"
is extremely costly.
If what you want is to just write five bytes to the end and proceed with your program, you have to pick a class that leaves some room for growth:
StringBuilder sb = new StringBuilder(5000);
for (; ; )
{
sb.Append("stuff");
}
StringBuilder
will auto-grow by doubling when it's limit is hit. So, you will see the growth pain once at start, once at 5,000 bytes, again at 10,000, again at 20,000. Appending strings will incur the pain every loop iteration.