Underscore.defaults vs. jQuery.extend vs. vanilla js (v2)

Revision 2 of this benchmark created on


Preparation HTML

<script src="//ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.8.2/underscore-min.js"></script>

Setup

var GameObject = {
        // init and other methods can be defined here
    };
    
    GameObject.prototype = {
        color: undefined,
        canKill: undefined,
        width: undefined,
        speed: undefined,
        weaponType: undefined
    };

Test runner

Ready to run.

Testing in
TestOps/sec
vanilla js
Object.prototype.extend = function (obj) {
    // source from this SO question: http://stackoverflow.com/questions/10430279/javascript-object-extending
    for (var i in obj) {
        if (obj.hasOwnProperty(i)) {
            this[i] = obj[i];
        }
    }
};

var ob1 = Object.create(GameObject);
ob1.extend({
    color: 'red',
    canKill: 'yes'
});

var ob2 = Object.create(GameObject);
ob2.extend({
    color: 'green',
    canKill: 'no',
    speed: 10
});
ready
Underscore defaults
var ob1 = _.defaults(Object.create(GameObject), {
    color: 'red',
    canKill: 'yes'
});

var ob2 = _.defaults(Object.create(GameObject), {
    color: 'green',
    canKill: 'no',
    speed: 10
});
ready
jQuery extend
var ob1 = $.extend(false, Object.create(GameObject), { 
    // false = no deep copy, new GameObject = target, source object
    color: 'red',
    canKill: 'yes'
});

var ob2 = $.extend(false, Object.create(GameObject), {
    color: 'green',
    canKill: 'no',
    speed: 10
});
ready
vanilla js 2
Object.prototype.extend = function (obj) {
    var keys = Object.keys(obj), i, keyLen = keys.length, key;
    for (i = 0; i < keyLen; ++i) {
         key = keys[i];
         this[key] = obj[key];
    }
};

var ob1 = Object.create(GameObject);
ob1.extend({
    color: 'red',
    canKill: 'yes'
});

var ob2 = Object.create(GameObject);
ob2.extend({
    color: 'green',
    canKill: 'no',
    speed: 10
});
ready

Revisions

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