why is this simple function slowing down, then crashing as time goes by
Here is the code:
Code:
private void button1_Click(object sender, System.EventArgs e)
{
string s="aaaaaaaaaaT";
for(int i=0;i<1000;i++)
{
func(ref s);
}
label1.Text = s;
}
private void func(ref string s)
{
s = s + s;
}
My machine has about 710 MB left in the harddrive. When this program runs and "i" variable is at around 20, the functions slows down and eventually stops/crashes. I look at the taskmanager and it shows that the memory usage is at maximum. Is there a way around this?
Re: why is this simple function slowing down, then crashing as time goes by
When something is slowing down and eventually crash it's usually a sign on a looping structure that does not end. However your code does end. The only thing I could think about is either the string is concatenating to a very large string that is sucking up your cpu or the label has a limit on the amount of characters it could hold.
What is the error message you got is there is any?
Re: why is this simple function slowing down, then crashing as time goes by
Your code first creates a String object that is 11 characters long. It then concatenates that String with itself to create a second string that is 22 characters long. It then creates a third String that is 44 characters long. By the time your code is finished it would have created 1000 String objects with each being twice as long as the one before it with the last being 11 * 2 ^1000 characters long. That's approximately 1.18 * 10 ^ 302 characters in the last String alone. With all the others as well there's almost twice that many. Gee, I can't see a problem with that. :rolleyes:
Re: why is this simple function slowing down, then crashing as time goes by
Quote:
Originally Posted by jmcilhinney
Your code first creates a String object that is 11 characters long. It then concatenates that String with itself to create a second string that is 22 characters long. It then creates a third String that is 44 characters long. By the time your code is finished it would have created 1000 String objects with each being twice as long as the one before it with the last being 11 * 2 ^1000 characters long. That's approximately 1.18 * 10 ^ 302 characters in the last String alone. With all the others as well there's almost twice that many. Gee, I can't see a problem with that. :rolleyes:
:D http://www.vbforums.com/images/ieimages/2006/04/1.gif
That's right, what he means "YOUR CODE IS EATING YOUR MEMORY" not your disk space
Re: why is this simple function slowing down, then crashing as time goes by
This is the most depressing thing I have ever seen. :D
Re: why is this simple function slowing down, then crashing as time goes by
I had a feeling it had something to do with memory. Thanks.
Re: why is this simple function slowing down, then crashing as time goes by
Don't forget to resolve your thread from the Thread Tools menu.