【算法】转载:Iterative vs. Recursive Approaches
Iterative vs. Recursive Approaches
Introduction
This article was originally posted at blogs.microsoft.co.il/blogs/Eyal.
Recursive function – is a function that is partially defined by itself and consists of some simple case with a known answer. Example: Fibonacci number sequence, factorial function, quick sort and more.
Some of the algorithms/functions can be represented in an iterative way and some may not.
Iterative
functions – are loop based imperative repetitions of a process (in
contrast to recursion which has a more declarative approach).
Comparison between Iterative and Recursive Approaches from Performance Considerations
Factorial

//recursive function calculates n!
static int FactorialRecursive(int n)
{
if (n <= 1) return 1;
return n * FactorialRecursive(n - 1);
} //iterative function calculates n!
static int FactorialIterative(int n)
{
int sum = 1;
if (n <= 1) return sum;
while (n > 1)
{
sum *= n;
n--;
}
return sum;
}
N | Recursive | Iterative |
10 | 334 ticks | 11 ticks |
100 | 846 ticks | 23 ticks |
1000 | 3368 ticks | 110 ticks |
10000 | 9990 ticks | 975 ticks |
100000 | stack overflow | 9767 ticks |
As we can clearly see, the recursive is a lot slower than the iterative (considerably) and limiting (stackoverflow).
The reason for the poor performance is heavy push-pop of the registers in the ill level of each recursive call.
Fibonacci

//--------------- iterative version ---------------------
static int FibonacciIterative(int n)
{
if (n == 0) return 0;
if (n == 1) return 1; int prevPrev = 0;
int prev = 1;
int result = 0; for (int i = 2; i <= n; i++)
{
result = prev + prevPrev;
prevPrev = prev;
prev = result;
}
return result;
} //--------------- naive recursive version ---------------------
static int FibonacciRecursive(int n)
{
if (n == 0) return 0;
if (n == 1) return 1; return FibonacciRecursive(n - 1) + FibonacciRecursive(n - 2);
} //--------------- optimized recursive version ---------------------
static Dictionary<int> resultHistory = new Dictionary<int>(); static int FibonacciRecursiveOpt(int n)
{
if (n == 0) return 0;
if (n == 1) return 1;
if (resultHistory.ContainsKey(n))
return resultHistory[n]; int result = FibonacciRecursiveOpt(n - 1) + FibonacciRecursiveOpt(n - 2);
resultHistory[n] = result; return result;
}
N | Recursive | Recursive opt. | Iterative |
5 | 5 ticks | 22 ticks | 9 ticks |
10 | 36 ticks | 49 ticks | 10 ticks |
20 | 2315 ticks | 61 ticks | 10 ticks |
30 | 180254 ticks | 65 ticks | 10 ticks |
100 | too long/stack overflow | 158 ticks | 11 ticks |
1000 | too long/stack overflow | 1470 ticks | 27 ticks |
10000 | too long/stack overflow | 13873 ticks | 190 ticks |
100000 | too long/stack overflow | too long/stack overflow | 3952 ticks |
As before, the recursive approach is worse than iterative however, we could apply memorizationpattern (saving previous results in dictionary for quick key based access), although this pattern isn't a match for the iterative approach (but definitely an improvement over the simple recursion).
Notes
- The calculations may be wrong in big numbers, however the algorithms should be correct.
- For timer calculations, I used
System.Diagnostics.Stopwatch
.
Points of Interest
- Try not to use recursion in system critical locations.
- Elegant solutions not always the best performing when used in "recursive situations".
- If you required to use recursion, at least try to optimize it with dynamic programming approaches (such as memorization).
转自:http://www.codeproject.com/Articles/21194/Iterative-vs-Recursive-Approaches
关于Tail Recursive
It is possible that recursion will be more expensive, depending on if the recursive function is tail recursive (last line is recursive call). Tail recursion should be recognized by the compiler and optimized to its iterative counterpart (while maintaining the concise, clear implementation you have in your code).
I would write the algorithm in the way that makes the most sense and is the most clear for the poor sucker (be it yourself or someone else) that has to maintain the code in a few months or years. If you run into performance issues, then profile your code, and then and only then look into optimizing by moving over to an iterative implementation. You may want to look into memoization and dynamic programming.
转自: http://stackoverflow.com/questions/72209/recursion-or-iteration
参考资料:
尾调用:
http://zh.wikipedia.org/wiki/%E5%B0%BE%E8%B0%83%E7%94%A8
http://en.wikipedia.org/wiki/Tail_call
【算法】转载:Iterative vs. Recursive Approaches的更多相关文章
- A* 寻路算法[转载]
A* 寻路算法 转载地址:http://www.cppblog.com/christanxw/archive/2006/04/07/5126.html 原文地址: http://www.gamedev ...
- ICP算法(Iterative Closest Point迭代最近点算法)
标签: 图像匹配ICP算法机器视觉 2015-12-01 21:09 2217人阅读 评论(0) 收藏 举报 分类: Computer Vision(27) 版权声明:本文为博主原创文章,未经博主允许 ...
- 【转】ICP算法(Iterative Closest Point迭代最近点算法)
原文网址:https://www.cnblogs.com/sddai/p/6129437.html.转载主要方便随时可以查看,如有版权要求请及时联系. 最近在做点云匹配,需要用c++实现ICP算法,下 ...
- GJM : 数据结构 - 轻松看懂机器学习十大常用算法 [转载]
转载请联系原文作者 需要获得授权,非法转载 原文作者将享受侵权诉讼 文/不会停的蜗牛(简书作者)原文链接:http://www.jianshu.com/p/55a67c12d3e9 通过本篇文章可以 ...
- 解读BloomFilter算法(转载)
1.介绍 BloomFilter(布隆过滤器)是一种可以高效地判断元素是否在某个集合中的算法. 在很多日常场景中,都大量存在着布隆过滤器的应用.例如:检查单词是否拼写正确.网络爬虫的URL去重.黑名单 ...
- 数据结构图之三(最短路径--迪杰斯特拉算法——转载自i=i++
数据结构图之三(最短路径--迪杰斯特拉算法) [1]最短路径 最短路径?别乱想哈,其实就是字面意思,一个带边值的图中从某一个顶点到另外一个顶点的最短路径. 官方定义:对于内网图而言,最短路径是指两 ...
- AStar算法(转载)
以下的文章来至http://blog.csdn.net/debugconsole/article/details/8165530,感激这位博主的翻译,可惜图片被和谐了,所以为方便阅读,我重新把图片贴上 ...
- 浅谈MySQL索引背后的数据结构及算法(转载)
转自:http://blogread.cn/it/article/4088?f=wb1 摘要 本文以MySQL数据库为研究对象,讨论与数据库索引相关的一些话题.特别需要说明的是,MySQL支持诸多存储 ...
- 展开BOM并使用最终用量的算法(转载)
本文系转载子ITPUB,如果有侵犯您权益的地方,烦请及时的告知与我,我即刻将停止侵权行为: 网址:http://www.itpub.net/thread-1020586-1-1.html http:/ ...
随机推荐
- Android反编工具的使用-Android Killer
今天百度搜索"Android反编译"搜索出来的结果大多数都是比較传统的教程.刚接触反编译的时候,我也是从这些教程慢慢学起的.在后来的学习过程中,我接触到比較方便操作的Android ...
- Loadrunner脚本编程(1)-大体思路
http://www.360doc.com/content/10/0806/13/1698198_44076570.shtml 就目前的了解.Loadrunner的脚本语言其实和C没什么区别.他内部的 ...
- RDD转换成DataFrames
官方提供了2种方法 1.利用反射来推断包含特定类型对象的RDD的schema.这种方法会简化代码并且在你已经知道schema的时候非常适用. 先创建一个bean类 case class Person( ...
- Google Volley框架之https请求
先插一句.Google出的volley框架本身是支持https请求的,可是仅仅是针对有第三方机构认证过的. 假设自己随便在网上搞的一个证书,那volley是不支持请求的. 本文讲下怎样让volley支 ...
- mybatis实现多表联合查询
本文转自:http://www.cnblogs.com/xdp-gacl/p/4264440.html#!comments 一.一对一关联 1.1.提出需求 根据班级id查询班级信息(带老师的信息) ...
- HDUOJ-----1085Holding Bin-Laden Captive!
Holding Bin-Laden Captive! Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/32768 K (Ja ...
- 安装Python 3.6
原文地址:https://www.liaoxuefeng.com/wiki/0014316089557264a6b348958f449949df42a6d3a2e542c000/00143160904 ...
- 【jQuery】将form表单通过ajax实现无刷新提交
//将form转换为AJAX提交 function ajaxSubmit(url,frm,fn){ var dataPara=getFormJson(frm); $.ajax({ url:url, t ...
- Yii2 mongodb 扩展的where的条件加入大于小于号浅析(转)
1. mongodb的where中有比较丰富的 条件,如下: static $builders = [ 'NOT' => 'buildNotCondition', 'AND' => 'bu ...
- 把git上的larave项目通过SourceTree安装上再通过composer安装依赖库
1.项目地址克隆 https://gitee.com/fps2tao/laravel5.5-alitaobao.git 通过SourceTree工具下载到本地 2.在命令行方式打开项目地址安装依赖库( ...