PHP Recursion vs Loops for Nested Properties

Hello, world!! During my recent project (php-json library), I had frequent scenarios where I had to choose between using regular loops or recursion to resolve each properties of a class and any embedded object properties. Ideally, the right way is to use the recursion as it is best suited for nested properties while loops can only go over a layer. So I took this option and utilised PHPs Reflection class to get the properties and recursively resolve them properly almost the same way a DI Container would. In another scenario, the loops will be the better choice as it has less space efficiency and doesn't stand a risk off stack overflow, perfect for huge sized data. In a nutshell, using recursion (especially with a logic to prevent infinite recursion) provides a logical and elegant code but isn't suited for working with large data, while loops work with large but simple one-layered data sets. Loops can also work with multiple layers, but will however, introduce badly nested for-loops which will eventually lead to code smells and bugs. Thank you for your time and have a productive week!! #Programming #CleanCode #SoftwareEngineering #DataStructures #Recursion

  • No alternative text description for this image

To view or add a comment, sign in

Explore content categories