Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using iterative style to clone an object in JavaScript

Is it possible to rewrite the following JavaScript recursive function to make it faster?

function clone_recursive(object) {
    var result = {};
    for (var key in object) {
        var value = object[key];
        if (typeof value === 'object') {
            result[key] = clone_recursive(value);
        } else {
            result[key] = value;
        }
    }
    return result;
}

I rewrote it in an iterative style but it doesn't gain any performance, in fact the speed dropped by ≈20%.

function clone_iterative(object) {
    var result = {};
    var queue = [{base: result, value: object}];
    var item;
    while (item = queue.shift()) {
        var current = item.value;
        var base = item.base;
        for (var key in current) {
            var value = current[key];
            if (typeof value === 'object') {
                var resultValue = base[key] = {};
                queue.push({base: resultValue, value: value});
            } else {
                base[key] = value;
            }
        }
    }
    return result;
}

http://jsperf.com/clone-an-object/13

like image 976
NVI Avatar asked Nov 25 '11 01:11

NVI


1 Answers

It's doubtable that an iterative version would truly be faster, as you're replacing a recursive call with multiple calls to queueing functions. Where a transformation to iteration helps is in preventing stack overflows (as call stacks tend to be smaller than heaps in interpreted languages), and with tail-recursion in languages without tail-call optimization.

like image 200
outis Avatar answered Oct 22 '22 10:10

outis