Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# Code running really slow

Tags:

c#

c#-4.0

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;
}
like image 246
Aman Avatar asked Sep 23 '26 09:09

Aman


2 Answers

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.

like image 100
Kevin DiTraglia Avatar answered Sep 27 '26 01:09

Kevin DiTraglia


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.

like image 43
MarcinJuraszek Avatar answered Sep 26 '26 23:09

MarcinJuraszek