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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With