This code snippet has already been through a few memory-related optimizations as the initial "bad" approach caused a typical stack overflow due to the basic recurs