JSON Object merger (v3)

Revision 3 of this benchmark created by Craig Thompson on


Preparation HTML

<script>
var Entity = function() {
        console.log('test');
};

Entity.defaults = {
        position: [0, 0],
        velocity: [0, 0],
        acceleration: [1, 1]
};

Entity.merge = function(obj1, obj2) {
        var cons = obj1.constructor,
                func = cons._mergeFunc, props, p, i;

        // Create the merge function if one isn't already defined
        if(!func) {
                func = '';

                // Loop over the first objects default properties and merge obj2's values
                if((props = cons.defaults)) {
                        for(p in props) {
                                func += 'if(typeof (val = obj2.'+p+') !== "undefined") {' +
                                        'obj.'+p+' = val.splice ? [ val[0], val[1], val[2] ] : val;' +
                                '} ';
                        }
                }

                // Create and store the new function
                func = cons._mergeFunc = new Function('obj', 'obj2', func);
        }

        // Run the merge function and return the first object
        return func(obj1, obj2), obj1;
};

Entity.mergeLoop = function(obj, obj2) {
        var props = obj.constructor.defaults;

        for(p in props) {
                if(typeof (val = obj2[p]) !== "undefined") {
                        obj[p] = val.splice ? [ val[0], val[1], val[2] ] : val;
                }
        }
}
</script>

Setup

var obj = new Entity();

Test runner

Ready to run.

Testing in
TestOps/sec
Dynamic-method merge
Entity.merge(obj, Entity.defaults);
ready
Iterative merge
Entity.mergeLoop(obj, Entity.defaults);
ready

Revisions

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