The following C# code takes 5 minutes to run:
int i = 1;
string fraction = "";
while (fraction.Length < 1000000)
{
fraction += i.ToString();
i++;
}
"Optimising it" like this causes it to run in 1.5 seconds:
int i = 1;
string fraction = "";
while (fraction.Length < 1000000)
{
// concatenating strings is much faster for small strings
string tmp = "";
for (int j = 0; j < 1000; j++)
{
tmp += i.ToString();
i++;
}
fraction += tmp;
}
EDIT: Some people suggested using StringBuilder
, which is an excellent suggestion also, and this comes out at 0.06s:
int i = 1;
StringBuilder fraction = new StringBuilder();
while (fraction.Length < 1000000)
{
fraction.Append(i);
i++;
}
Playing around to find the optimum value of j
is a topic for another time, but why exactly does this non-obvious optimisation work so well? Also, on a related topic, I've heard it said that you should never use the +
operator with strings, in favour of string.Format()
, is this true?