Object Cycle Detection (v2)

Revision 2 of this benchmark created by vjeux on


Preparation HTML

<script>
  /* Build the recursive object */
  function generateRecursiveObject(n) {
    var root = {};
    var obj = root;
    for (var i = 0; i < n; ++i) {
      obj['child'] = {};
      obj = obj['child'];
    }
    obj['child'] = root;
    return root;
  }
  var o100 = generateRecursiveObject(100);
  var o1000 = generateRecursiveObject(1000);
  var o10000 = generateRecursiveObject(10000);
  
  
  function CycleDetection() {
    this.seenObjects = [];
  }
  CycleDetection.prototype = {
    detect: function (obj) {
       if (typeof obj === 'object') {
         if ('mark' in obj) {
           return false;
         }
         obj.mark = true;
         this.seenObjects.push(obj);
         for (var key in obj) {
           if (obj.hasOwnProperty(key) && !this.detect(obj[key])) {
             return false;
           }
         }
       }
       return true;
    },
  
    test: function (obj) {
      var result = this.detect(obj);
      for (var i = 0; i < this.seenObjects.length; ++i) {
        delete this.seenObjects[i].mark;
      }
      return result;
    }
  }
  
  
  var isNativeJSON = typeof JSON !== 'undefined' && JSON.stringify.toString().match(/\{ \[native code\] \}$/);
  if (isNativeJSON) {
    JSONCycleDetection = function (obj) {
      try {
        JSON.stringify(obj);
        return true;
      } catch (e) {
        return false;
      }
    }
  } else {
    JSONCycleDetection = function (obj) {
      throw 'Not native JSON.stringify';
    }
  }
</script>

Test runner

Ready to run.

Testing in
TestOps/sec
[100] Javascript Cycle Detection
(new CycleDetection).test(o100);
ready
[100] Native JSON Cycle Detection
JSONCycleDetection(o100);
ready
[1000] Javascript Cycle Detection
(new CycleDetection).test(o1000);
ready
[1000] Native JSON Cycle Detection
JSONCycleDetection(o1000);
ready
[10000] Javascript Cycle Detection
(new CycleDetection).test(o10000);
ready
[10000] Native JSON Cycle Detection
JSONCycleDetection(o10000);
ready

Revisions

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

  • Revision 1: published by vjeux on
  • Revision 2: published by vjeux on
  • Revision 3: published by vjeux on