!Good!
I have a simple piece of code that I can't understand very well what is happening...
static void Main(string[] args)
{
string cadena = "lore";
for(int i=0; i<1000000; i++)
{
cadena += "lore";
}
Console.WriteLine(cadena);
}
What it does is easy to figure out. Simply chain the word in the variable a million times and then it should display it on the console.lore
cadena
I highlight the should because it doesn't. And this is what I don't understand, why doesn't it show the result, and keep the program running? And how can I make it show it?
I have tried to give it a spin... And the logic that I find is that it exceeds the limit of characters that a can have string
, but since no type of exception is thrown, it makes me doubt.
Any idea why this happens, and how to fix it?
I suspect that the problem is not the maximum size allowed
string
in .net (theoretically 2,147,483,647 characters, the max. size ofInt32
, although this is not entirely true), but a property ofstrings
.net and other languages: they are immutable.On each iteration of your loop a new string is being created in memory, and this is making it extremely slow.
To do what you ask, you must use
StringBuilder
, which represents a mutable string . Look at this example:By using
StringBuilder
you are not creating astring
on every interaction, and it will work as you expect.