[英]Impact of using recursions in Java
I have written a sample Java class and used recursion for a specific purpose in a method. 我编写了一个示例Java类,并在方法中将递归用于特定目的。 I have displayed the code below of the particular recursion method (please note that I have mentioned here only the required part from the method).
我在下面显示了特定递归方法的代码(请注意,我在这里仅提及了该方法的必需部分)。
private String checkForDuplicateCVs(final Integer userId) throws SQLException {
//
// Codes to obtain the cvSerialId comes here...
//
final Integer cvCount = (Integer) getSqlMapClient().queryForObject("user.getCvCountBySerialId", cvSerialId);
if (cvCount != 0) {
checkForDuplicateCVs(userId);
}
It is appreciated if someone could help me to figure out the impact of using recursions in a java program and whether it's a good practice or bad practice. 如果有人可以帮助我弄清楚在Java程序中使用递归的影响以及它是好习惯还是坏习惯,我将不胜感激。 If it's a bad practice then what are the negative impacts.
如果这是一个不好的做法,那么负面影响是什么。
Recursion is not bad in itself, and in fact it's often the best way to design an algorithm. 递归本身并不坏,实际上,它通常是设计算法的最佳方法。
That said, in your case I'd say it's poor design. 就是说,在您的情况下,我会说这是糟糕的设计。 You essentially have a
while
loop that you've implemented with recursion. 本质上,您有一个使用递归实现的
while
循环。
There are a few possible problems with this: 这可能有一些问题:
while
loop, but in your case that will eventually reach the stack limit and throw an exception. while
循环来说,这是完全可以的,但是在您的情况下,最终将达到堆栈限制并引发异常。 This would make your use of recursion a bug, one that in my opinion has security implications (Denial-of-Service). while
loop and a recursive implementation of that while
loop you'll see a large performance gap. while
循环和递归实现,它的while
循环,你会看到一个大的性能差距。 It's possible to optimize this away in some circumstances (namely tail recursion), but not always. The only dark side of recursion is that you may get a StackOverflowException, if your function will call itself large number of times (you may modify stack size with JVM parameter). 递归的唯一弊端是,如果函数将自己多次调用(您可以使用JVM参数修改堆栈大小),则可能会收到StackOverflowException。 Note that the recursion may always be replaced with a simple while loop.
请注意,递归始终可以用简单的while循环替换。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.