object inheritance vs object composition (v2)

Revision 2 of this benchmark created on


Preparation HTML

<script>
// ## [Github Repo](https://github.com/Raynos/pd)

// pd converts all the values of the properties into propertydescriptors
var pd = function _pd(obj) {
    var keys = Object.keys(obj);
    var o = {};
    keys.forEach(function _each(key) {
        var pd = Object.getOwnPropertyDescriptor(obj, key);
        o[key] = pd;
    });
    return o;
};

// merges merges all objects passed in. The later objects take preference in clashes
pd.merge = function _merge() {
    var o = {};
    for (var k in arguments) {
        var obj = arguments[k];
        Object.keys(obj).forEach(function _each(key) {
            o[key] = obj[key];
        });
    }
    return o;
};

// object is an Object.create shortcut. Consider it an improved object literal.
pd.object = function _obj(o) {
    return Object.create(Object.prototype, pd(o));
};

var addPropertyProxy = function(target, source, key) {
    Object.defineProperty(target, key, {
        "get": function _get() {
            return source[key];    
        },
        "enumerable": true,
        "configurable": true  
    }); 
};

pd.proxy = function _proxy() {
    var o = {};
    for (var k in arguments) {
        var obj = arguments[k];
        Object.keys(obj).forEach(function _each(key) {
            addPropertyProxy(o, obj, key);
        });  
    }
    return o;
};

if ("undefined" !== typeof module && module.exports) {
    module.exports = pd;
} else {
    window.pd = pd;
}
</script>

<script>
  var lower  = {
    "foo": "bar"
  };
  
  var upper = {
    "bar": "foo"
  };
  
  var combined = Object.create(lower,  pd(upper));
  
  function Lower() {
        this.foo = "bar";
  }
  
  Upper.prototype = new Lower();
  Upper.prototype.constructor = Upper;
  function Upper() {
        this.bar = "foo";
  }
  
  var c1 = Object.create(combined);
  
  var c2 = Object.create(pd.merge(lower, upper));
  
  var c3 = Object.create(pd.proxy(lower, upper));
  
  var o1 = Object.create(c1);
  var o2 = Object.create(c2);
  var o3 = Object.create(c3);
  var o4 = new Upper();
  
  
 var fn = function(val){
       return Math.random() + val;
};

</script>

Test runner

Ready to run.

Testing in
TestOps/sec
test inheritance
fn(o1.foo);
ready
test composition
fn(o2.foo);
ready
test proxy
fn(o3.foo);
ready
test new
fn(o4.foo);
ready

Revisions

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