31
you are viewing a single comment's thread
view the rest of the comments
[-] jjagaimo@lemmy.ca 18 points 9 months ago

It depends on if the problem is recursive or iterative, and how much it needs to be optimized.

For example, you may use a for loop for a simple find and replace scheme for characters in a string, where you check each character one by one until you find one which matches the target, and then substitute that.

There are certainly recursive ways to do string replacement in strings which might be faster than an iterative search depending on implementation, but that's more optimization than I might need 99.9999% of the time

A recursive problem that's difficult to solve iteratively is browsing all the files in a folder and it's subfolders. Each folder may have several subfolders, which you then need to search, but then each of those folders can have subfolders. This problem can be solved fairly easily recursively but not as easily iteratively.

That's not to say it can't be solved that way, but the implementation may be easier to write

Recursive code, however, is more frequently prone to bugs which causes infinite recursion leading to crashes, as it is not a tool which is often used and requires several more fences to prevent issues. For example, in the folder example, if one were to encounter a shortcut to another folder and implement code to follow that shortcut as if it were a directory as well, then placing a shortcut to a folder within itself might cause the code to recurse infinitely without having a maximum recursion depth and or checking for previously seen folders.

[-] Nommer@sh.itjust.works 4 points 9 months ago

Could your folder tree problem also be solved with a whole loop instead? I'm very new but it seems like recursion is harder but possibly more optimized approach to loops or am I incorrect here?

[-] mercator_rejection@programming.dev 8 points 9 months ago

Any recursive algorithm can be made iterative and vise versa. It really depends on the algorithm if the function calls are a major factor in performance.

load more comments (4 replies)
load more comments (5 replies)
this post was submitted on 22 Dec 2023
31 points (91.9% liked)

Programming

17025 readers
128 users here now

Welcome to the main community in programming.dev! Feel free to post anything relating to programming here!

Cross posting is strongly encouraged in the instance. If you feel your post or another person's post makes sense in another community cross post into it.

Hope you enjoy the instance!

Rules

Rules

  • Follow the programming.dev instance rules
  • Keep content related to programming in some way
  • If you're posting long videos try to add in some form of tldr for those who don't want to watch videos

Wormhole

Follow the wormhole through a path of communities !webdev@programming.dev



founded 1 year ago
MODERATORS