Recursion or Iteration?

前端 未结 30 2400
小鲜肉
小鲜肉 2020-11-22 14:44

Is there a performance hit if we use a loop instead of recursion or vice versa in algorithms where both can serve the same purpose? Eg: Check if the given string is a palind

30条回答
  •  -上瘾入骨i
    2020-11-22 15:31

    Using just Chrome 45.0.2454.85 m, recursion seems to be a nice amount faster.

    Here is the code:

    (function recursionVsForLoop(global) {
        "use strict";
    
        // Perf test
        function perfTest() {}
    
        perfTest.prototype.do = function(ns, fn) {
            console.time(ns);
            fn();
            console.timeEnd(ns);
        };
    
        // Recursion method
        (function recur() {
            var count = 0;
            global.recurFn = function recurFn(fn, cycles) {
                fn();
                count = count + 1;
                if (count !== cycles) recurFn(fn, cycles);
            };
        })();
    
        // Looped method
        function loopFn(fn, cycles) {
            for (var i = 0; i < cycles; i++) {
                fn();
            }
        }
    
        // Tests
        var curTest = new perfTest(),
            testsToRun = 100;
    
        curTest.do('recursion', function() {
            recurFn(function() {
                console.log('a recur run.');
            }, testsToRun);
        });
    
        curTest.do('loop', function() {
            loopFn(function() {
                console.log('a loop run.');
            }, testsToRun);
        });
    
    })(window);
    

    RESULTS

    // 100 runs using standard for loop

    100x for loop run. Time to complete: 7.683ms

    // 100 runs using functional recursive approach w/ tail recursion

    100x recursion run. Time to complete: 4.841ms

    In the screenshot below, recursion wins again by a bigger margin when run at 300 cycles per test

提交回复
热议问题