对求N的阶层问题,递归与非递归算法进行讨论,以下为两段代码:
递归算法:
private void Form1_Load(object sender, EventArgse)
{
int n = 25;
long result;
result = fax(n);
MessageBox.Show(result.ToString());
}
private long fax(int n)
{
if (n <= 0)
return 1;
return (long)n* fax(n - 1); ;
}
非递归算法:
private void Form1_Load(object sender, EventArgse)
{
intn = 25;
long result = 1;
for (inti = n; i > 1; i--)
{
result = result * i;
}
MessageBox.Show(result.ToString());
}
转换为汇编语言如下: (标示出下面分析的部分)
递归算法:
{
// 代码大小 27 (0x1b)
.maxstack 2
.locals init ([0]int64 result)
IL_0000: nop
IL_0001: ldarg.0
IL_0002: ldsfld int32 '测试汇编'.Form1::n
IL_0007: call instance int64 '测试汇编'.Form1::fax(int32)
IL_000c: stloc.0
IL_000d: ldloca.s result
IL_000f: call instance string [mscorlib]System.Int64::ToString()
IL_0014: call valuetype [System.Windows.Forms]System.Windows.Forms.DialogResult[System.Windows.Forms]System.Windows.Forms.MessageBox::Show(string)
IL_0019: pop
IL_001a: ret
} // end of method Form1::Form1_Load
非递归算法:
{
// 代码大小 45 (0x2d)
.maxstack 2
.locals init ([0]int64 result,
[1]int32 i,
[2] boolCS$4$0000)
IL_0000: nop
IL_0001: ldc.i4.1
IL_0002: conv.i8
IL_0003: stloc.0
IL_0004: ldsfld int32 '测试汇编2'.Form1::n
IL_0009: stloc.1
IL_000a: br.s IL_0017
IL_000c: nop
IL_000d: ldloc.0
IL_000e: ldloc.1
IL_000f: conv.i8
IL_0010: mul
IL_0011: stloc.0
IL_0012: nop
IL_0013: ldloc.1
IL_0014: ldc.i4.1
IL_0015: sub
IL_0016: stloc.1
IL_0017: ldloc.1
IL_0018: ldc.i4.1
IL_0019: cgt
IL_001b: stloc.2
IL_001c: ldloc.2
IL_001d: brtrue.s IL_000c
IL_001f: ldloca.s result
IL_0021: call instance string [mscorlib]System.Int64::ToString()
IL_0026: call valuetype[System.Windows.Forms]System.Windows.Forms.DialogResult[System.Windows.Forms]System.Windows.Forms.MessageBox::Show(string)
IL_002b: pop
IL_002c: ret
} // end of method Form1::Form1_Load
相同编译器,相同优化级别,不同代码 | ||
| 递归 | 非递归 |
代码量 | 少 | 多 |
堆栈使用(根据我们实际的知识,递归需要更多的栈,因为要不断的出入栈,但是从反编译出的汇编语言来看,栈更少,可能是自己的某些地方理解不对) | 少 | 多 |
耗时 | 多 | 少 |
如何从汇编中,分析堆栈的使用,这个我也看不懂,求知道的人提醒提醒,,,,谢谢
明显:非递归比递归的速度快很多。