Aman
Aman

Reputation: 602

C# Code running really slow

Hy, I have a int[] x with 10000 indexes, and I`m using a code like this to put every value in a newline in a textbox, but my code will take atleast a couple minuts to fill the textbox, is there a quickier way to do the same?

for ( int x = 0; X < 10000; x++)
{
    textBox1.Text += randomNumber[x] + Environment.NewLine;
}

Upvotes: 2

Views: 198

Answers (3)

Kevin DiTraglia
Kevin DiTraglia

Reputation: 26058

Yes, use a string builder for things like this:

StringBuilder builder = new StringBuilder(10000); 
for (int x = 0; x < 10000; x++)
{
    builder.AppendLine(randomNumber[x]);
}
textBox1.Text = builder.ToString();

Otherwise you are 'coughing up a string', a common pitfall to new programmers. Here is a great blog post from Joel Spolsky describing common pitfalls with strings and immutability.

Upvotes: 8

MarcinJuraszek
MarcinJuraszek

Reputation: 125630

It's not clear whether randomNumber collection size is 10000 or not, but if it is, you can use String.Join method:

textBox1.Text = string.Join(Environment.NewLine, randomNumber);

It will use StringBuilder internally anyway, but is better to read.

Upvotes: 2

RyanR
RyanR

Reputation: 7758

Build the string first, then put its value in the textbox (instead of appending text to the text box 10,000 times).

Upvotes: 0

Related Questions