在C#中,在算法中使用递归函数是一种很好的做法吗? [英] In C# is it a good practice to use recursive functions in algorithms?

查看:131
本文介绍了在C#中,在算法中使用递归函数是一种很好的做法吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在许多使用递归的函数式语言中被认为是一个很好的习惯。我认为这是很好的,因为编译器优化了函数式语言的代码。

但是,在创建算法时,在C#中使用递归是否是一种很好的做法?对于C#来说,说递归算法会导致堆栈的增长速度相当快(如果调用的数量非常大),并且这样做不会很快,并且可能导致堆栈溢出。或者也有一些优化发生,使递归函数有效?

我会感激,如果你会提供一些比较(速度,内存,可读性)算法之间使用递归函数式语言和C#。

解决方案

不使用递归会导致你用你自己的堆栈重写你的算法,它会最终在执行时受到类似的条件。

您可以根据您的算法需要自定义堆栈大小,但是如果您查看WPF / Silverlight和正常的UI相关算法,它们都是递归的,每次点击,每次按键和每个通知都会经过很多递归方法。



查看使用自定义堆栈大小创建线程



尽管速度可能因算法和复杂程度而异但是创建单独的非递归算法会使任务更加复杂,因为您将使用列表,堆栈等来完成所有数据存储操作。

这是相当的设计vs性能问题,如果你想获得更好的性能,那么你的非递归算法会更快地执行,但是设计和实现这样的算法需要更长的时间。如果你想要更快的解决方案,那么你还可以编写递归算法,但执行速度会更慢,但如果差异只有几毫秒或几微秒,那么它就不值得这样做。


In many functional languages using a recursion is considered to be a good practice. I think it is good because of the way compiler optimizes functional language's code.

But is it a good practice to use recursion in C#, when creating an algorithm? Is it right to say in regards to C#, that recursive algorithms will result in your stack growing quite dramatically (if the amount of calls is very big) and this won't be any fast at all, and might result in stack overflow. Or there are also some optimization happening to make recursive functions efficient?

I would appreciate if you would give some comparison (speed, memory, readability) between algorithms which uses recursion in Functional languages and C#.

解决方案

Not using recursion will anyway cause you to rewrite your algorithm using your own "Stack", which will eventually be subjected to similar conditions while execution.

You can customize stack size based on need of your algorithm, but if you look at WPF/Silverlight and normal UI related algorithms, they all are recursive in nature and every click, every key press and every notifications go through lot of recursive methods.

Check out Creating Thread with Custom Stack Size,

Although the speed may vary depending upon the algorithm and complexity, but creating separate non recursive algorithm will make task more complex as you will be doing all data store operations by yourself using lists, stacks etc.

This is quite design vs performance issue, if you want better performance, then your non recursive algorithm will execute faster, but it will take longer to design and implement such algorithm. Where else if you want a quicker solution then you can write recursive algorithm that will be slower in execution but if the difference is only few milliseconds or microseconds then its not worth doing it.

这篇关于在C#中,在算法中使用递归函数是一种很好的做法吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆