简体   繁体   中英

Impact of using recursions in Java

I have written a sample Java class and used recursion for a specific purpose in a method. 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. 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.

There are a few possible problems with this:

  • Readability and code maintenance. It's a loop, why obfuscate it?
  • Susceptibility to stack overflow. Your recursive call takes the same parameter as the parent, so it's entirely possible that you'll get an infinite loop if the database doesn't change. That's perfectly fine for a while loop, but in your case that will eventually reach the stack limit and throw an exception. This would make your use of recursion a bug, one that in my opinion has security implications (Denial-of-Service).
  • This doesn't apply to your code, but in general function calls are much more expensive than simple loops. Therefore if you compare the execution times of a while loop and a recursive implementation of that while loop you'll see a large performance gap. It's possible to optimize this away in some circumstances (namely tail recursion), but not always. (this effect is negligible in your code because the database query is far far more expensive than the function call overhead)

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). Note that the recursion may always be replaced with a simple while loop.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM