I’m trying to optimize code that I have. In order to do that, I wrote this code to see the effect of recursion vs. iteration. The code “counts” to 10-to-the-n’th power.
public Form1()
{
InitializeComponent();
Stopwatch sw = new Stopwatch();
sw.Start();
recurse(4);
//iterate(4);
sw.Stop();
Text = sw.Elapsed.TotalMilliseconds.ToString();
}
void recurse(int i)
{
if (i < 1) return;
for (int x = 0; x < 10; x++) recurse(i - 1);
}
void iterate(int i)
{
i = (int)System.Math.Pow(10, i);
for (int x = 0; x < i; x++) ;
}
I’m getting this unexpected result: when n is 1 through 4 the speed is around 0.5 ms for both recursion and iteration. -Instead of 4 being 1000 times slower than 1 which is what I expected. Only for greater numbers does it start to have a more intuitive speed, the iteration also being faster than the recursion.
Why the same speed for 10 times as for 10,000 times?
Even if you do correct the code to calculate the same thing in both cases, do not test things like that in one run. You’re not going to get a proper result unless the test itself takes at least a second. Run it one million times and then divide the total time. When you’re testing something that’s going to take only a millisecond or two, you should make sure the test takes long enough to ignore the differences of cold cache, times of .Start() and .Stop() calls, small GC delay in the meantime, etc. Also make sure the actual work takes more time than empty counting loop (that is
for(many times) recurse(x)has high enoughxthat theforitself is not relevant)Your result of 0.5ms in a single run is more or less meaningless here. Also if it’s a jitted language, I’d recommend calling the same function before testing, to ensure it’s already compiled – otherwise it’s going to add overhead.
TL;DR – overhead of other things happening around your function is higher than the time your function takes to execute.