Improving the efficiency of a C# loop
Pregunta
I am making a program that estimates pi through increasing the number of sides of a polygon with a given radius to an extremely high number, taking the area, and dividing it by the radius squared. I have the following:
double radius = 5;
for (double sides = 3;sides < 10000;sides++)
{
double pi_est = ((radius * radius * sides * Math.Sin((360 / sides)*(Math.PI/180))) / 2) / (radius * radius);
richTextBox1.AppendText(pi_est+"\n");
}
As of now, this takes about 5 seconds to complete. Is there anything I could re write that would improve the efficiency of my loop?
Solución
That AppendText
call is going to cost a lot of time because it implies accessing the UI. Accumulate the string using a StringBuilder
or an array with String.Join
instead.
You should never use a double
as an iteration variable; use an int
instead (that's less of an efficiency problem and more of a potential gotcha).
radius*radius
cancels out -- note that pi
is independent of the radius used, so you can just assume the radius is equal to 1 and ignore it.
All written out:
StringBuilder sb = new StringBuilder();
for(int sides = 3; sides < 10000; sides++) {
double pi_est = sides * Math.Sin((2*Math.PI)/sides) / 2;
sb.append(pi_est + "\n");
}
richTextBox1.AppendText(sb.ToString());
Otros consejos
For starters you could precalculate radius * radius outside the loop.
Also if not needed inside the loop update your rich text box once outside the loop and just use a StringBuilder inside.