递归与非递归算法的分析

对求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

 

相同编译器,相同优化级别,不同代码

 

递归

非递归

代码量

堆栈使用(根据我们实际的知识,递归需要更多的栈,因为要不断的出入栈,但是从反编译出的汇编语言来看,栈更少,可能是自己的某些地方理解不对)

耗时

如何从汇编中,分析堆栈的使用,这个我也看不懂,求知道的人提醒提醒,,,,谢谢


明显:非递归比递归的速度快很多。


 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值