{"id":115,"date":"2011-05-06T07:54:23","date_gmt":"2011-05-06T14:54:23","guid":{"rendered":"http:\/\/sloanseaman.com\/wordpress\/?p=115"},"modified":"2011-07-17T10:01:59","modified_gmt":"2011-07-17T17:01:59","slug":"recursion-is-as-recursion-does","status":"publish","type":"post","link":"http:\/\/sloanseaman.com\/wordpress\/2011\/05\/06\/recursion-is-as-recursion-does\/","title":{"rendered":"Recursion is as Recursion does"},"content":{"rendered":"<p>Recursion.  It&#8217;s one of those questions you see in most interview questions. Usually it&#8217;s in the context of something like &#8216;Calculate Fibonacci numbers&#8217; or something along those lines with the intent of determining if you understand recursion.  Its a great question to ask but at the same time the answer itself is actually very wrong if you were going to do it in the real world.<\/p>\n<p>Recursion has it&#8217;s place (Sorts, Binary Tree traversal, etc) but don&#8217;t just use it because it makes the code smaller.  Think about the cost of recursion.  Every call:<\/p>\n<ul>\n<li>Adds an object to the call stack<\/li>\n<li>Allocates more memory<\/li>\n<li>Sometimes throws readability right out the window (and down the block, making a left at the mailbox)<\/li>\n<li>Eats up CPU time<\/li>\n<\/ul>\n<p>A coworker of mine (Jay Palat) just recently wanted to dust off his python skills.  To do this he decided to code a fun little problem: Get a list of all the even Fibonacci numbers.  Now, being a good developer he immediately took to it with recursion like so:<\/p>\n<pre class=\"brush: python; light: false; title: ; wrap-lines: false; notranslate\" title=\"\">\r\n#!\/usr\/bin\/python\r\n\r\n&quot;&quot;&quot;Each new term in the Fibonacci sequence is generated by adding the previous two terms. By starting with 1 and 2, the first 10 terms will be:\r\n\r\n1, 2, 3, 5, 8, 13, 21, 34, 55, 89, ...\r\n\r\nBy considering the terms in the Fibonacci sequence whose values do not exceed four million, find the sum of the even-valued term&quot;&quot;&quot;\r\n\r\ndef fib(n):\r\n    if n == 0 :\r\n        return 1\r\n    if n == 1 :\r\n        return 2\r\n    return fib(n-1) + fib(n-2)\r\n  \r\n&quot;&quot;&quot;for n in range(0,10):\r\n    print fib(n)\r\n&quot;&quot;&quot;\r\nitem = 0\r\nsum = 0\r\nfib_item = fib(item)\r\nwhile fib_item &lt; 40000000:\r\n    if fib_item%2==0:\r\n        print &quot;Even item: &quot; + str(fib_item)\r\n        sum = sum + fib_item\r\n    item = item + 1\r\n    fib_item = fib(item)\r\nprint &quot;Sum: &quot; + str(sum)\r\nprint &quot;Final item : &quot; + str(item)   \r\n<\/pre>\n<p>Don&#8217;t worry about the style or overall approach.  The thing to know is that this method, which I dare say most developers would take, uses recursion.  In the end this method took, on average, 47 seconds to execute (going up to 40000000).<\/p>\n<p>For each call you have two recursive calls. This means you have at least three entries on the call stack per call, which then has three, and then three&#8230;. welcome to recursion.  Honestly, we discussed the Big O on this and realized we weren&#8217;t that good at Big O and moved on \ud83d\ude09<\/p>\n<p>I then said: &#8216;Why not do it without recursion?  Sure it might not be as cool, might not be as small, but is should use a lot less memory and CPU&#8217;.<\/p>\n<p>This is what was coded (stripped down):<\/p>\n<pre class=\"brush: python; light: false; title: ; wrap-lines: false; notranslate\" title=\"\">\r\nold_number = 1\r\ncurrent_number = 1\r\nnext_number = 0\r\nsum = 0\r\nwhile current_number &lt; 40000000:\r\n    print current_number\r\n    if current_number%2 == 0:\r\n        sum = sum + current_number\r\n    next= current_number + old_number\r\n    old_number = current_number\r\n    current_number = next\r\n    \r\nprint &quot;Sum :&quot; + str(sum)\r\n<\/pre>\n<p>And the total execution time for this : 0.027 seconds.<\/p>\n<p>Lets state that again:<br \/>\nOld way with recursion: 47 seconds<br \/>\nNew way without recursion: 0.027 seconds<\/p>\n<p>Without the recursion we didn&#8217;t have the stack overhead, the additional memory usage, or any of the additional CPU cycles.<\/p>\n<p>So, the next time you think of recursion, think of performance as well. You might even respond in the interview: &#8220;Do you want me to just show recursion, or do you want me to make it fast and efficient?&#8221;<\/p>\n","protected":false},"excerpt":{"rendered":"<p>Recursion. It&#8217;s one of those questions you see in most interview questions. Usually it&#8217;s in the context of something like &#8216;Calculate Fibonacci numbers&#8217; or something along those lines with the intent of determining if you understand recursion. Its a great &hellip; <a href=\"http:\/\/sloanseaman.com\/wordpress\/2011\/05\/06\/recursion-is-as-recursion-does\/\">Continue reading <span class=\"meta-nav\">&rarr;<\/span><\/a><\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":[],"categories":[10],"tags":[],"_links":{"self":[{"href":"http:\/\/sloanseaman.com\/wordpress\/wp-json\/wp\/v2\/posts\/115"}],"collection":[{"href":"http:\/\/sloanseaman.com\/wordpress\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"http:\/\/sloanseaman.com\/wordpress\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"http:\/\/sloanseaman.com\/wordpress\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"http:\/\/sloanseaman.com\/wordpress\/wp-json\/wp\/v2\/comments?post=115"}],"version-history":[{"count":4,"href":"http:\/\/sloanseaman.com\/wordpress\/wp-json\/wp\/v2\/posts\/115\/revisions"}],"predecessor-version":[{"id":168,"href":"http:\/\/sloanseaman.com\/wordpress\/wp-json\/wp\/v2\/posts\/115\/revisions\/168"}],"wp:attachment":[{"href":"http:\/\/sloanseaman.com\/wordpress\/wp-json\/wp\/v2\/media?parent=115"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"http:\/\/sloanseaman.com\/wordpress\/wp-json\/wp\/v2\/categories?post=115"},{"taxonomy":"post_tag","embeddable":true,"href":"http:\/\/sloanseaman.com\/wordpress\/wp-json\/wp\/v2\/tags?post=115"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}