List analysis - Recursion vs Loop (v3)

Revision 3 of this benchmark created by L8D on


Description

A comparison of the speed of looping through an array, or taking the functional programming approach of recursive pathing.

This kind of performance only applies to JavaScript. These kind of operations are highly optimized via tail-call elimination and shared-memory in truly functional languages like Clojure or Haskell(in fact, this is how you would usually loop through lists).

Setup

// array is a range from 0 to 30000: [0, 1, 2, 3, 4, ... 29999, 30000]
    var arr = [];
    for (var i = 0; i <= 30000; i++) arr.push(i);
    
    // No-operation preventing function
    var noNOP = function(x) {
      return x;
    };
    
    var recur = function(list) {
      if (list.length === 0) return;
      noNOP(list[0]);
      recur(list.slice(1));
    };
    
    var looped = function(list) {
      for (var i = 0, l = list.length; i < l; i++) {
        noNOP(list[i]);
      }
    };

Test runner

Ready to run.

Testing in
TestOps/sec
Recursive
recur(arr);
ready
For loop
looped(arr);
ready

Revisions

You can edit these tests or add more tests to this page by appending /edit to the URL.