by Edward
31 December 2010 09:44
When using recursions in Applications, you should always think about why you are not using iterations. Non-optimised code within the loops can result in exacerbated performance issues, ranging from increased memory usage to CPU spikes, causing your application to slow down or fail. You should also consider replacing recursion with looping, because each recursion adds data to stack. You should always study your code for recursive calls that can be converted to a ‘loop’ equivalent.
The following code snippet makes use of recursive calls to accomplish a small task of string concatenation.
static Array arr = GetArrayOfStrings();
static int index = arr.Length - 1;
String finalStr;
public Validate()
{
finalStr = Recursive(index);
}
/// <summary>
/// Recursives the specified index.
/// </summary>
/// <param name="index">The index.</param>
/// <returns></returns>
string Recursive(int index)
{
if (index <= 0)
{
return string.Empty;
}
else
{
return (arr.GetValue(index) + Recursive(index - 1));
}
}
private static Array GetArrayOfStrings()
{
//code here
}
Rewritten, the following code now avoids creating new data on the stack for each successive call and avoids an additional method call to itself.
static Array arr = GetArrayOfStrings();
static int index = arr.Length - 1;
String finalStr;
/// <summary>
/// Concates the specified array.
/// </summary>
/// <param name="array">The array.</param>
/// <returns></returns>
string Concate(Array array)
{
StringBuilder sBuilder = new StringBuilder();
for (int i = array.Length; i > 0; i--)
{
sBuilder.Append(array.GetValue(i));
}
return sBuilder.ToString();
}
private static Array GetArrayOfStrings()
{
//code here
}
The following key points summarises how you can improve iteration and loop efficiency(From MSDN):
- Avoid repetitive field or property access.
- Optimize or avoid expensive operations within loops.
- Copy frequently called code into the loop.
- Consider replacing recursion with looping.
- Use for instead of foreach in performance-critical code paths.